I have a nested list to loop through in pre Java 8
. My example is very similar to loop through nested list in java 8 which is a great example to follow then I realized that I need to check for null
for each list
. Plz refer to the below example. If the last condition is met then return true by short-circuiting.
However I am not sure how to check null
for each list
using list.stream().flatMap()
.
for(A a : ListA) {
if(a.getListB() != null && !a.getListB().isEmpty()) {
for(B b : a.getListB()) {
if(b.getListC() != null && !p.getListC().isEmpty()) {
for(C c : b.getListC()) {
return (c.name.equalsIgnoreCase("john"));
}
}
}
}
}
This is kind of gross but it works. You essentially check if listB is not null and create a Stream of B. Then filter through Stream of B and check if ListC is null and if not map to a Stream of C. Then just simply check if any of C match the argument.
boolean found = listA.stream()
.filter(a -> a.getListB() != null)
.flatMap(a -> a.getListB().stream())
.filter(b -> b.getListC() != null)
.flatMap(b -> b.getListC().stream())
.anyMatch(c -> c.name.equalsIgnoreCase("john"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.