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

Map example in java

I would like to write lastnamesByFirstname method.
In the people lists, there are bunch of people, and each person have two field the firstname and the second name. I would like to write a method which will turn back in the following way, key value would be the firstname, and the value list would be those name which firstnames are the same. I tried with groupingby wiht sorting buts somehow never worked.

* {
     *  "Mary" -> ["Smith", "Silver"]
     *  "Joe" -> ["Smith"]
     * }
     */
    static Map<String, List<String>> lastnamesByFirstname(List<Person> people){
        
}

my attempt look like this, but the type would be not matching with the return type.

var peopleStream= people.stream()
                .collect(groupingBy(Person::getFirstName));

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

>Solution :

In the second parameter of groupingBy, you can transform List<Person> to List<String> using mapping:

var peopleStream = people.stream()
        .collect(groupingBy(Person::getFirstName,
                mapping(Person::getLastName, Collectors.toList())));
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