计算java中对象的列表变量的值

时间:2018-04-30 18:41:28

标签: java java-stream

我有一个对象Student

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>();

我想算一下有多少学生上了特定班级。看起来像

math: 2
physics: 2
chemistry: 2

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

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

1 个答案:

答案 0 :(得分:3)

将其展平然后分组。

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