Java 8 collection streaming - Convert list to Set, convert result

Imaging object with the following method:

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

      

I now have collection A as input; And I want to get a lot of unique IDs from it, generally you would like:

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 the stream API, for example by following

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

      

but making a flat set B

+3


source to share


1 answer


You must use flatMap

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

      



This will create a flat set.

+8


source







All Articles