Java 8 - collect list attributes using Set <?> Type as set of values

I have List<Entity> entites;

where Entity has fields called testField with type Set:

class Entity {
    Set<String> testField;
}

      

I want to get all the Strings that are contained in all TestFields in the entites list; So if I don't use java 8 my woud code looks like lile:

Set<String> allTestFieldString = newHashSet();
for(Entity entity : entities) {
    allTestFieldString.addAll(entity.testField);
}

      

The following code doesn't compile for me:

entites.stream().map(entity -> entity.testField()).collect(Collectors.toSet());

      

Thanks any help, thanks!

+3


source to share


1 answer


You need flatMap

to create a stream of all elements of all testField

Sets:



Set<String> allTestFieldString = entites.stream().flatMap(entity -> entity.testField.stream()).collect(Collectors.toSet())

      

+5


source







All Articles