Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Collections max size with count

I have a class like below.

class Student {
    public Student(Set<String> seminars) {
        this.seminar = seminars;
    }
    Set<String> seminar;
    public Set<String> getSeminar()
    {
        return seminar;
    }
}

And created a set of students like below.

List<Student> students = new ArrayList<Student>();
Set<String> seminars = new HashSet<String>();

seminars.add("SeminarA");
seminars.add("SeminarB");
seminars.add("SeminarC");

students.add(new Student(seminars)); //Student 1 - 3 seminars
students.add(new Student(seminars)); //Student 2 - 3 seminars

seminars = new HashSet<String>();
seminars.add("SeminarA");
seminars.add("SeminarB");

students.add(new Student(seminars)); //Student 3 - 2 seminars

seminars = new HashSet<String>();
students.add(new Student(seminars)); //Student 4 - 0 seminars

Now the question is "I'm trying to get the count of students who has atteneded maximus seminars" As you can see there are 2 students who has attended to 3(maximum) seminars, So I needed to get that count.

I achieved the same using 2 different statements using stream

OptionalInt max = students.stream()
    .map(Student::getSeminar)
    .mapToInt(Set::size)
    .max();
long count = students.stream()
    .map(Student::getSeminar)
    .filter(size -> size.size() == max.getAsInt())
    .count();

is there a way to achieve the same using one statement?

like image 562
Suryaprakash Pisay Avatar asked Mar 08 '23 08:03

Suryaprakash Pisay


1 Answers

To solve this, please use the follwing code:

students.stream()
    .map(Student::getSeminar)
    .collect(Collectors.groupingBy(Set::size, Collectors.counting()));

Your output will be:

{0=1, 2=1, 3=2}

As you can see, there are two students that are going to the maximum number of seminars which is three.

First we changed all the students objects from the stream with the actual sets and then we used Collectors groupingBy() method to group the sets by size.

If you want to get only the number of the students, please use following code:

students.stream()
    .map(Student::getSeminar)
    .collect(Collectors.groupingBy(Set::size, Collectors.counting()))
    .values().stream()
    .max(Comparator.comparing(a->a))
    .get();

Your output will be: 2.

like image 188
Alex Mamo Avatar answered May 15 '23 21:05

Alex Mamo