在一个循环或两个单循环中在哈希图的哈希图中输入数据

时间:2018-07-07 23:30:20

标签: java

我有以下类型的列表:RepoID,Userid,事件计数(8种类型)

示例:

Repoid1, user1,8,1,0,2,3,4,5,9
Repoid1, user2,5,6,0,0,0,4,5,9
Repoid2, user1,5,0,5,2,3,4,5,1
Repoid3, user4,0,6,9,2,3,4,5,2

对于每个回购,我想查找用户的每种事件类型的计数。 我正在使用hashmap的hashmap,但由于文件太大,我不想使用2个循环。有没有办法在单个循环中执行此操作或使用2个单个循环?

我当前正在使用2个循环:

for (int i = 0; i < data.size(); i++) { //data is an arraylist
    String[] seq = data.get(i).split(",");
    String repo=seq[0];
    for (int j = 0; j < data.size(); j++) {
        seq = data.get(j).split(",");
        if(seq[0].equals(repo)){
            usermap.put(seq[1],"seq[2] + "," + seq[3] + "," + seq[4] + "," + seq[5] + 
                "," + seq[6]    + "," + seq[7] + "," + seq[8] + "," + seq[9]");
        } 
    }
    RepoUserMap.put(repo, EventsMap);
}

1 个答案:

答案 0 :(得分:0)

您的问题描述不清楚,但是给定您的输入文件,以下内容可能满足您的需求:

HashMap<String, HashMap<String, String>> repoUserMap = new HashMap<>();

for (int i = 0; i < data.size(); i++) { //data is an arraylist
    String[] seq = data.get(i).split(",");
    String repo = seq[0];

    // Lookup the 2nd-level map, and create it if it doesn't exist yet.
    HashMap<String, String> userMap = repoUserMap.get(repo);
    if (userMap == null) {
        userMap = new HashMap<>();
        repoUserMap.put(repo, userMap);
    }

    usermap.put(seq[1],"seq[2] + "," + seq[3] + "," + seq[4] + "," + seq[5] + 
            "," + seq[6]    + "," + seq[7] + "," + seq[8] + "," + seq[9]");
 }

带有注释的中间部分是(概念上)您所缺少的部分。


如果需要合并来自同一用户并回购的多个输入行中的计数,则可以在循环的最后一行进行。但是,您的代码,示例或说明中没有指出这一点,因此我假设不需要。

我还要指出,如果您这样做是为了可以快速查找计数,那么您应该将它们存储为整数数组,而不是每次查找时都需要拆分和解析的字符串计数。