Java 8 stream - how to find parent entity from child?

gtludwig :

I have a scenario similar to:

public class A {
    private String id;
    @ManyToMany
    private Set<B> bSet;
    // getters and setters
}

and

public class B {
    private String id;
    // other attributes
    // getters and setters
}

How can I find an instance of A when I have an instance of B using the stream() API? I was trying something like:

public A findAFromB(B b) {
    List<A> aList = aService.findAll();
    Optional<A> matchingObject = aList.stream().filter({find a where a.getBSet().contains(b)}).getA();
return (A) matchingObject.get();
}

How to properly write this filter?

Naman :

Soemthing like using a findFirst or findAny as a terminal operation:

Optional<A> matchingObject = aList.stream()
        .filter(a -> a.getbSet().contains(b))
        .findFirst();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115464&siteId=1