1

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

1
  • Unfortunately not. If course you could do it with streams, but you would also have to use a data structure to count the occurrences - a HashMap like you suggested. And streams also iterate over the values, meaning you gain nothing. For large HashMaps you might have a benefit using parallelStream though. Commented Sep 5, 2016 at 9:18

1 Answer 1

9

Use Collectors.groupingBy like this

Map<String,Long> groupByGrades=  grades.values().stream().
      collect(Collectors.groupingBy(Function.identity(),    
      Collectors.counting()));
Sign up to request clarification or add additional context in comments.

1 Comment

Java 11 example on the Oracle docs, docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/… uses summingInt

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.