dexhunter
dexhunter

Reputation: 578

count values of a list variable of an object in java

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

Upvotes: 2

Views: 1326

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

flatten it then group.

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

Upvotes: 3

Related Questions