hashmap java中arraylist的和值

时间:2016-07-06 05:22:13

标签: java arraylist

我想在arraylist中对hashmap java的值求和。以下是我的代码:

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));
}

输入键和值如下:

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

结果如下:

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

我希望结果像这样出来:

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

如何对arraylist中相同键的hashmap中的每个值求和?

1 个答案:

答案 0 :(得分:1)

我想我会这样做:

    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();

输入:

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

输出:

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