Arian
Arian

Reputation: 7749

Convert a List of objects to a Map using Streams

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

Upvotes: 1

Views: 198

Answers (2)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

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:

Upvotes: 4

9000
9000

Reputation: 40894

You never told the collector to extract last names.

I suppose you need something like

list.stream
  .collect(groupingBy(
    A::getFirstName, // The key is extracted.
    mapping(  // Map the stream of grouped values.
      A::getLastName, // Extract last names.
      toSet()  // Collect them into a set.
)));

Upvotes: 2

Related Questions