2

I have an object 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>();

I want to count how many students have a particular class. Something look like

math: 2
physics: 2
chemistry: 2

I tried to use stream but it's still array of strings thus the wrong answer, I wonder if I can get single string? Thank you.

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

1 Answer 1

3

flatten it then group.

students.stream()   
        .flatMap(s -> Arrays.stream(s.getClasses()))  
        .collect(Collectors.groupingBy(Function.identity(),    
                            Collectors.counting()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.