Reputation: 33
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
Upvotes: 1
Views: 9022
Reputation: 9623
Use Collectors.groupingBy
like this
Map<String,Long> groupByGrades= grades.values().stream().
collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Upvotes: 9