我有一个对象学生
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/