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()));
asked Sep 18, 2019 at 21:33

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:

answered Sep 18, 2019 at 21:42
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.
)));
answered Sep 18, 2019 at 21:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.