Java 8 Stream filtering value of list in a list
I saw the accepted answer from @kocko which is both a good answer and totally correct. However there is a slightly alternative approach where you simply chain the filters.
final List<MyObject> withBZ = myObjects.stream()
.filter(myObj -> myObj.getType().equals("B"))
.filter(myObj -> myObj.getSubTypes().stream().anyMatch("Z"::equals))
.collect(Collectors.toList());
This is basically doing the same thing but the &&
operand is removed in favour of another filter. Chaining works really well for the Java 8 Stream API:s and IMO it is easier to read and follow the code.
You can do:
myObjects.stream()
.filter(t -> t.getType().equals(someotherType) &&
t.getSubTypes().stream().anyMatch(<predicate>))
.collect(Collectors.toList());
This will fetch all the MyObject
objects which
- meet a criteria regarding the
type
member. - contain objects in the nested
List<String>
that meet some other criteria, represented with<predicate>