0

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"));
                    }
                }
            }
        }
    }

1 Answer 1

3

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.