user1862784 user1862784 - 1 year ago 61
Java Question

Group by values in map using java streams

I have map of student grades in a class, i want to get count by grade, it can be done by iterating the values and then increasing count in a map is there better way using Streams.

Map<String, String> grades = new HashMap();
grades.put("100", "A");
grades.put("101", "B");
grades.put("102", "A");
grades.put("103", "C");
grades.put("104", "D");
grades.put("105", "B");
grades.put("106", "B");
grades.put("107", "C");

my Output map should have A=2, B=3, C=2, D=1

Answer Source

Use Collectors.groupingBy like this

Map<String,Long> groupByGrades=  grades.values().stream().