Search code examples
javalistsortingcollectionsjava-stream

Java - order a collections by number of objects in each list?


 Collection<List<Person>> personsByDepartment=
                persons.stream()
                        .collect(Collectors.groupingBy(Person::getDepartment))
                        .values();

I have the following Collection above that groups a list of People into lists based off their department. This is working as expected.

How can I ensure this list is sorted so that the list with most amount of people in it is first?


Solution

  • Provide a Comparator to compare the lists by their size. You could stream the values again to sort:

    Collection<List<Person>> personsByDepartment = persons.stream()
                .collect(Collectors.groupingBy(Person::getDepartment))
                .values()
                .stream()
                .sorted((l1, l2) -> Integer.compare(l2.size(), l1.size()))
                .collect(Collectors.toList());
    

    Edit: As Michael pointed out in comments the same comparator can be written as:

    Comparator.<List<Person>>comparingInt(List::size).reversed()
    

    It's more obvious, that the ordering is being reversed.