2017-10-17 39 views
-5

我有一系列的表決結果列表(長形式),例如:如何從長更改數據的廣泛形式的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

回答

0

這裏是一個將重新格式化數據

這是假設你的數據的方法{["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; 
}