How to sum values Java Hashmap

Znaczki :

I need some help, i was trying to get the sum of the values but im stuck map values i want to sum

Grades grades = new Grades(Arrays.asList(1,2,3,4));
Grades grades2 = new Grades(Arrays.asList(2,3,4,5));
Grades grades3 = new Grades(Arrays.asList(4,5,6,1));
Grades grades4 = new Grades(Arrays.asList(1,2,2,4));

HashMap<Pupil, Grades> map = new HashMap<Pupil, Grades>();
map.put(pupil, grades);
map.put(pupil1, grades2);
map.put(pupil2, grades3);
map.put(pupil3, grades4);

I tried to do it by using for-each

int sum = 0;
for (int a : map.values()) {
    sum += a;
}

But im getting an error "incompatible types: Grades cannot be converted to int, line 49"

class Grades{

    private List<Integer> grades;

    public Grades(List<Integer> grades){
        this.grades = grades;
    }
}
azro :

The method HashMap.values() returns a Collection<V> so here a Collection<Grades>, so when iterating you got a Grade. Then each Grade has a list of int

int sum = 0;
for (Grades g : map.values()) {
    for(int a : g.getGrades()){ // use the getter name you have in Grade class
        sum += a;
    }
}

Using Streams it'll look like

 int sum = map.values()                    // Collection<Grades>
              .stream()                    // Stream<Grades>
              .map(Grades::getGrades)      // Stream<List<Integer>>
              .flatMap(List::stream)       // Stream<Integer>
              .mapToInt(Integer::intValue) // IntStream
              .sum();                      // int

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=299950&siteId=1