繁体   English   中英

使用java流在map中按值分组

[英]Group by values in map using java streams

我在课堂上有学生成绩的地图,我想按年级计算,可以通过迭代值来完成,然后在地图中增加计数是否有更好的方法使用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");

我的输出图应该有A = 2,B = 3,C = 2,D = 1

使用Collectors.groupingBy就像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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