'How to extract an object from a List of object in Java 8?

I have a list of object A (Folder). Each object A in this list has a list of object B (Partners) and the object B has also a list of Object C (Personnes). The object C contains an attribute code that i want to use to filter using java 8.

I've tried the code bellow but it doesnt seem to work :

A objectA = new A();
String code = "O";
for (A a: listObjectsA) {
    for (B b: a.getPartners()) {
        for (C c: b.getPersonnes()) {
            if (c.getCode().equalsIgnoreCase(code)) {
                objectA = a;
                break;
            }
        }
    }
}

Do you guys have an idea how can i use FlatMap to do this kind of conversion from List<A> to A ?



Solution 1:[1]

We use filter on the top-level stream, checking inner streams using anyMatch as your search is to find any matching object:

A objectA = listObjectsA.stream().filter(a -> a.getPartners()
                .stream()
                .anyMatch(b -> b.getPersonnes()
                        .stream()
                        .anyMatch(c -> c.getCode().equalsIgnoreCase(code)))) 
        .findFirst()
        .orElseGet(A::new); //defaults to new A()

You can't use a simple flatMap as it'd transform the stream to B and C types in turn, making it rather complicated to return to the parent A object you want to return.

Solution 2:[2]

It does not work because the break instruction stops just the last for loop.

You can use break with a label that stops exactly the loop you want.

A objectA = new A();
String code = "O";
loopA: for (A a: listObjectsA) {
    for (B b: a.getPartners()) {
        for (C c: b.getPersonnes()) {
            if (c.getCode().equalsIgnoreCase(code)) {
                objectA = a;
                break loopA;
            }
        }
    }
}

You can encapsulate the method using return and Optional.

public class Example {

    public String getObjectA() {
        String code = "O";
        for (A a: listObjectsA) {
            for (B b: a.getPartners()) {
                for (C c: b.getPersonnes()) {
                    if (c.getCode().equalsIgnoreCase(code)) {
                        return Optional.of(a);
                    }
                }
            }
        }
        return Optional.empty();
    }

    public static void main(String[] args) {
        Optional<A> objectA = getObjectA();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ernest_k
Solution 2