如何在 Java 中将数据从长格式更改为宽格式

How to change data from long to wide form in 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   

谁能解释一下如何做到这一点?

这是一种重新格式化数据的方法

这是假设您的数据是 {["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;
}