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

隐身守侯 提交于 2019-12-11 02:45:43

问题


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?


回答1:


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

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


来源:https://stackoverflow.com/questions/56288707/java-8-stream-how-to-find-parent-entity-from-child

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!