Sum values of arraylist in hashmap java

风流意气都作罢 提交于 2019-12-20 05:45:06

问题


I want to sum values of arraylist in hashmap java. Following is my code:

Map hm = new HashMap();
for(int i=0; i<dataArray().length; i++){
    Arraylist valueHashMap = new Arraylist();
    valueHashMap.add(0, aArray[i]);
    valueHashMap.add(1, bArray[i]);
    valueHashMap.add(2, cArray[i]);

    if (hm.containsKey(dArray[i])){
        Arraylist newOne = new Arraylist();
        newOne.add(hm.get(dArray[i]));
        valueHashMap.add(newOne);
        hm.put(dArray[i], valueHashMap);
    }else{
        hm.put(dArray[i], valueHashMap);
    }
}
Iterator iterator = hm.keySet().iterator();
while(iterator.hasNext()){
String key = iterator.next().toString();
System.out.println(key + " " + hm.get(key));
}

Input keys and values are like this:

1 : 1, 2, 3
2 : 4, 5, 6
1 : 1, 2, 3

The results come out like this:

1 : [1, 2, 3, [[1, 2, 3]]]
2 : [4, 5, 6]

I want result to come out like this:

1 : [2, 4, 6]   //summary of values in arraylist of same key
2 : [4, 5, 6]

How should I sum each values in arraylist of same key in hashmap?


回答1:


I think I would've done like this:

    Scanner sc = new Scanner(System.in);
    Map<String, int[]> m = new HashMap<>();
    int n = 3;
    for (int i = 0; i < n; i++) {
        String[] s = sc.nextLine().split("[,\\s:]+");
        int[] arr = new int[s.length - 1];
        boolean cn = m.containsKey(s[0]);
        for (int j = 0; j < arr.length; j++) {
            arr[j] = Integer.parseInt(s[j + 1]) + ((cn) ? m.get(s[0])[j] : 0);
        }
        m.put(s[0], arr);
    }
    for (String s : m.keySet()) {
        System.out.println(s + " : " + Arrays.toString(m.get(s)));
    }
    sc.close();

Input:

1 : 1, 2, 3
2 : 4, 5, 6
1 : 1, 2, 3

Output:

1 : [2, 4, 6]
2 : [4, 5, 6]


来源:https://stackoverflow.com/questions/38216806/sum-values-of-arraylist-in-hashmap-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!