Return city in which most people live - stream()

Viewed 156

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?

2 Answers

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

As suggested by @Thomas above, use a grouping collector with counting collector to collect the number of persons by city and then look for the city with the higest count value:

         Optional<String> result = persons.stream()
                .collect(Collectors.groupingBy(Person::getCity, Collectors.counting())) // Map<String, Long>: Key -> city, Value -> count of persons with such city
                .entrySet().stream()
                .max(Map.Entry.comparingByValue()) // looking for highest count value
                .map(Map.Entry::getKey);
Related