简体   繁体   中英

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

Use Collectors.groupingBy like this

Map<String,Long> groupByGrades=  grades.values().stream().
      collect(Collectors.groupingBy(Function.identity(),    
      Collectors.counting()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM