我有一个班级的学生成绩表,我想按年级进行计数,可以通过迭代值然后在图中增加计数来实现,这是使用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()));

关于java - 使用Java流按 map 中的值分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39327312/

10-11 20:09