0

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?

6
  • In your code, hm.containsKey(dArray[i]), you are adding the array to the list. I think this is where you need to SUM the values of the array elements. Commented Jul 6, 2016 at 5:32
  • what are dataArray, aArray, bArray and cArray Commented Jul 6, 2016 at 6:06
  • They are string arrays. Commented Jul 6, 2016 at 6:11
  • @Yuki probably show us a trimmed down version of what these arrays contain? Commented Jul 6, 2016 at 6:19
  • All of the arrays are contained double values. Commented Jul 6, 2016 at 6:22

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

I can't write <>, : symbol.
@Yuki what? why not?
I have no idea! I developed Java on websphere studio application developer and Java version is J2RE 1.4.1, Java platform is 5.1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.