Collect all the values ​​of the Set field

I have a collection that has a field of type Set with some values. I need to create a new set that collects all these values.

I am wondering if this is possible with lambda expressions.

The following is a line of code:

Set<String> teacherId = batches.stream()
                               .filter(b -> !CollectionUtils.isEmpty(b.getTeacherIds()))
                               .map(b -> b.getTeacherIds())
                               .collect(Collectors.toSet());

The problem is the post map operation, it contains a set of rows. Thus, the collection operation returns a Set<Set<String>>, but I want to aggregate all the values ​​into a single set.

+6
source share
4 answers

You need to use flatMapinstead map:

Set<String> teacherIds = 
    batches.stream()
           .flatMap(b -> b.getTeacherIds().stream())
           .collect(Collectors.toSet());

, - , . getTeacherIds() null, . filter(Objects::nonNull) , Apache Commons.

+7

flatMap Stream , Set<String>:

Set<String> teacherId = 
    batches.stream()
           .filter(b -> !CollectionUtils.isEmpty(b.getTeacherIds()))
           .flatMap(b -> b.getTeacherIds().stream())
           .collect(Collectors.toSet());
+2

, getTeacherIds() , !=, CollectionUtils.isEmpty . , getTeacherIds() , flatMap, .

  Set<String> teacherIds = batches
            .stream()
            .filter(x -> x.getTeacherIds() != null)
            .flatMap(x -> x.getTeacherIds().stream())
            .collect(Collectors.toSet());
+2

I am wondering if this is possible with lambda expressions.

I grab the last fish :).

Set<String> teacherIds = batches.stream()//v--- the class of `x`
                                .map(XClass::getTeacherIds)
                                .filter(Objects::nonNull)
                                .flatMap(Collection::stream)
                                .collect(Collectors.toSet());

Note. Sorry, I forgot to tell you, if you getTeacherIdscopy the internal identifiers to a new set of identifiers, the above code is suitable for you. since it reads identifiers from XClassonce.

+1
source

All Articles