Collect all values of a Set field

Biscuit Coder :

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

I am wondering if this is possible using lambda expressions.

Below is the code line :

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

The problem is post map operation, it contains a collection of set of strings. So collect operation returns a Set<Set<String>> but i am looking to aggregate all the values to a single set.

Mureinik :

You need to use flatMap instead of map:

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

Note that the filtering is redundant for empty collections - streaming an empty collection will just result in an empty stream, which won't affect the final result. If getTeacherIds() could return null, however, you'd still have to handle it. Using filter(Objects::nonNull) would suffice, and save you the dependency on Apache Commons.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464533&siteId=1