3

Imaging object with following method:

class A { List<B> getIds(){...} }

Now I have an Collection of A as input; And I want to get set of unique Ids out of it, normally you would go for:

Set<B> ids = new HashSet<>();
for(A a : input){
  ids.addAll(a.getIds());
}

Is there a way to do the same in one line using stream API, like following

Set<List<B>> set = input.stream().map((a) -> a.getIds()).collect(Collectors.toSet());

but making flat set of B

Igor Piddubnyi
  • 134
  • 4
  • 19
  • Why is question marked as a duplicate? I know the question and answers are very similar, but a Set and List are not the same thing. – Kraagenskul Jan 11 '18 at 15:03

1 Answers1

9

You have to use flatMap

input.stream()
    .map(a -> a.getIds())
    .flatMap(ids -> ids.stream())
    .collect(Collectors.toSet());

This will produce flat Set.

ByeBye
  • 6,650
  • 5
  • 30
  • 63