0

I am trying to add up all the values for any Hashmap. The hash map will have two Integers. First as a key and the second as a value. I am getting errors in the compiler as I am not sure how to do this. I want to return the total value of all the values in the hash map.

I would like this method to work for any hash map that I place into this method's parameter and return

I am a 7th grader trying to learn java on my own at the moment. If someone can show me how to also run this in a main method with a passed in hash map that would be super.

I am getting these errors: Multiple markers at this line - value cannot be resolved to a type - Type mismatch: cannot convert from element type Integer to value - Line breakpoint:PopulationTotal [line: 10] - getTotal(HashMap) - Syntax error, insert "Identifier" to complete EnhancedForStatementHeaderInit

I am trying this:

public int getTotal (HashMap<Integer, Integer> p) {
    for (value : p.values()) {
        int total += value;
    }
    return total
}
Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
  • 4
    Does this answer your question? [How to sum values from Java Hashmap](https://stackoverflow.com/questions/21665538/how-to-sum-values-from-java-hashmap) – Morne Dec 08 '19 at 06:47
  • 4
    You need to declare `total` before the loop, not inside it. – Guy Dec 08 '19 at 06:48
  • Just declare `total` before the `for` loop. – Moshi Dec 08 '19 at 06:50
  • Side note: use interfaces not implementation classes as method parameters, wherever possible (Map instead of HashMap). – Puce Dec 08 '19 at 08:04

2 Answers2

1

You have to declare type of the for-each variable.
Also, initialize total as 0 outside the loop.
Try this:

public int getTotal (HashMap<Integer, Integer> p) {
int total = 0;
for (int value : p.values()) {
    total += value;
}
return total
}
Dhyey Shah
  • 582
  • 7
  • 23
1

Or shorter this way :

public int getTotal (HashMap<Integer, Integer> p) {
    return p.values().stream().mapToInt(Integer::intValue).sum();
}

Thank's to Stream API, JAVA 8 provides functional programming capabilities. But the paradigm is a little bit different from classical programming

kevin ternet
  • 4,514
  • 2
  • 19
  • 27