1

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

2 Answers 2

4
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:

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.