java - java中对象的列表变量的计数

标签 java java-stream

我有一个对象学生

public class Student {
    protected final String name;
    protected final String[] classes;

    public Student(String name; String[] classes) {
        this.name = name;
        this.classes = classes;
    }

    //getter & setters
}

Student a = new Student("A", new String[]{"math", "physics"});
Student b = new Student("B", new String[]{"math", "chemistry"});
Student c = new Student("C", new String[]{"physics", "chemistry"});

List<Student> students = new ArrayList<Student>();

我想计算特定类(class)有多少学生。看起来像的东西

math: 2
physics: 2
chemistry: 2

我尝试使用stream,但它仍然是字符串数组,因此是错误的答案,我想知道我是否可以获得单个字符串?谢谢。

Map<String[], Long> map = students.stream()
    .collect(Collectors.groupingBy(Student::getClasses, 
    Collectors.counting()))

最佳答案

将其压平然后分组。

students.stream()   
        .flatMap(s -> Arrays.stream(s.getClasses()))  
        .collect(Collectors.groupingBy(Function.identity(),    
                            Collectors.counting()));

关于java - java中对象的列表变量的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50106370/

相关文章:

Java Stream - 编译时错误 - 类型与 Map<Integer,List<String>> 不匹配 : cannot convert from Map<Object, Object>

用于 map 的 Java 8 流收集器,误导性分组错误

JavaFX 场景在 Windows 10 上的场景构建器和运行时中的缩放比例不同

java - Java 中的处理器乘法器

java - 迭代具有自引用的对象

java - 一个流中的多个 "match"检查

Java 8 - 使用 startsWith 从列表中过滤字符串 X 并将字符串 X 保存到列表

java - 在 android 中实现推荐技术/应用程序邀请的最佳方式?

java - 将列表合并为具有唯一元素的单个数组

java - java中两个日期字符串的区别