如何从长更改数据的广泛形式的Java

问题描述:

我有一系列的表决结果列表(长形式),例如:如何从长更改数据的广泛形式的Java

List<String[]> results=new ArrayList<>(); 

Vote | User | Poll 
Yes | 121 | 1  //each poll is on its own line 
No | 123 | 1 
Yes | 121 | 2 

,我试图让我的数据宽形式:

Poll1Vote | Poll2Vote | User 
Yes  | Yes  | 121 //this has all polls on one line for user 121 
No  | NULL  | 123 

有人可以解释如何做到这一点?

+0

莫非谁投票决定关闭这解释了为什么目前还不清楚? – Rilcon42

+0

你只是在寻找一种方式来转换特定的数据(使用更多的String [3]条目)? (我不是近距离投票) – phflack

+0

是的,我从来没有尝试过在Java中进行数据统计,并且无法正确格式化数据 – Rilcon42

这里是一个将重新格式化数据

这是假设你的数据的方法{["Yes", "121", "1"], ...}

你可能需要一些小的调整,如果你的数据被格式化为{["Vote", "User", "Poll"], ["Yes", "121", "1"], ...}


此功能通过首先计算出UserPoll

一旦知道有多少总用户(输出列表长度),总投票(输出数组长度),它可以搭配在一起对他们来说,并建立输出

List<String[]> format(List<String[]> input) 
{ 
    List<String[]> output = new ArrayList<String[]>(); 
    Set<String> users = new HashSet<String>(); 
    Set<String> pollSet = new HashSet<String>(); 
    Map<String, String> data = new HashMap<String, String>(); 

    for(String[] row : input) //figure out how many users and polls there are 
    { 
     users.add(row[1]); 
     pollSet.add(row[2]); 
     data.put(row[1] + "_" + row[2], row[0]); //link user_poll to Yes/No data 
    } 

    String[] polls = pollSet.toArray(new String[0]); //make the set be an array for easier access 
    Arrays.sort(polls); //sort the polls here if you want to 

    for(String user : users) //loop over users, since each row is 1 user 
    { 
     String[] row = new String[polls.length + 1]; //each row is poll1,poll2,...,pollN,user 
     row[row.length - 1] = user; 

     for(int i = 0; i < polls.length; i++) 
      row[i] = data.get(user + "_" + polls[i]); //retrieve the Yes/No data for user_poll, no data fills in null 
      //alternative if you want "NULL" instead of null 
      //if((row[i] = data.get(user + "_" + polls[i]) == null) 
       //row[i] = "NULL"; 

     output.add(row); //add completed row to the output 
    } 

    return output; 
}