Search code examples
javajava-streamjava-17

Return city in which most people live - stream()


I have a class called Person (name,surname,city,age) and I added to it persons.

I have to find the city that lives the most people - in my case is "Meerdonk". I tried using stream(), but I cannot figure out how.

This is my code:

 public static Optional<Person> getMostPopulateCity(List<Person> personList) {
     return personList.stream()
            .filter(person -> person.getCity()
            // here
            .max(Comparator.comparing(Person::getCity));
   }

At // here, I don't know what I should do to get my most populated city, and if max. is OK to be used, as I want to get the max (most populated city).

Can someone explain me please what I should use to get out the most populated city? Or just to let me know what I have wrong?


Solution

  • You can use Collectors.groupingBy to group persons by city, then extract the map entry with the most people like so (assuming cities are strings):

    return personList.stream()
            .collect(Collectors.groupingBy(Person::getCity)) // Map<String, List<Person>>
            .entrySet().stream()
            .max(Comparator.comparing(e -> e.getValue().size())) // Optional<Map.Entry<String, List<Person>>
            .map(Entry::getKey);