Java – collect all values of the set field

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

I wonder if it is feasible to use lambda expressions

The following 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 the post map operation, which contains a set of strings Therefore, the collection operation returns set < set < string > > but I want to summarize all values into one set

Solution

You need to use @ L_ 419_ 0 @ instead of map:

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

Note that for empty sets, filtering is redundant - streaming empty sets will only lead to empty streams, which will not affect the final result However, if getteacherids () can return null, you still need to deal with it Using filter (objects:: nonnull) is enough, and you can save the dependency on Apache Commons

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>