Reputation: 550
I have an Object with multiple fields. One of the fields is a List<Object2>
.
I want to recuperate a List (or a Set because I don't need the duplicated) of all the names (Object2.getName()
) of the items Object2.
I tried to do it as follows:
getList().stream()
.map(Object::getListObject2)
.collect(Collectors.toSet())
.stream()
.flatMap(List::stream)
.collect(Collectors.toSet());
It returns a Set<Object2>
, but not a Set/List<Object2.getName()>
.
Also, I'm concerned about the complexity of the stream.
Thank you.
Upvotes: 2
Views: 132
Reputation: 121008
getList().stream()
.flatmap(x -> x.getListObject2().map(Object2::getName))
.collect(Collectors.toSet());
Upvotes: 1
Reputation: 811
You don't need to collect then re-stream. Just call getName. How about this ?
getList().stream()
.map(Object::getListObject2)
.flatMap(List::stream)
.map(Object2::getName)
.collect(Collectors.toSet());
Upvotes: 3