Convert a List of objects to a Map using Streams

Arian :

I have a list of objects of class A:

List<A> list;
class A {
    String name;
    String lastname;
    //Getter and Setter methods
}

I want to convert this list to a map from name to a set of lastnames:

Map<String, Set<String>> map;

For example, for the following list:

John Archer, John Agate, Tom Keinanen, Tom Barren, Cindy King

The map would be:

John -> {Archer, Agate}, Tom -> {Keinanen, Barren}, Cindy -> {King}

I tried the following code, but it returns a map from name to objects of class A:

list.stream.collect(groupingBy(A::getFirstName, toSet()));
Fullstack Guy :
Map< String, Set<String>> map = list.stream()
                                    .collect(
                                        Collectors.groupingBy(
                                              A::getFirstName, Collectors.mapping(
                                                    A::getLastName, Collectors.toSet())));

You were on the right track you need to use:

  • Collectors.groupingBy to group by the firstName.

  • And then use a downstream collector like Collectors.mappping as a second parameter of Collectors.groupingBy to map to the lastName .

  • And then finally collect that in a Set<String> by invoking Collectors.toSet:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324790&siteId=1