user3450862
user3450862

Reputation: 550

How to retrieve a Set of String from the field of each element in a List of objects that is contained in an object?

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

Answers (2)

Eugene
Eugene

Reputation: 121008

 getList().stream()
          .flatmap(x -> x.getListObject2().map(Object2::getName))
          .collect(Collectors.toSet());

Upvotes: 1

lbndev
lbndev

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

Related Questions