Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading