我有一个类似的场景:
public class A {
private String id;
@ManyToMany
private Set<B> bSet;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
和
public class B {
private String id;
// other attributes
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
A当我有B使用stream()API 的实例时,如何查找实例?我正在尝试类似的东西:
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();
}
Run Code Online (Sandbox Code Playgroud)
如何正确编写此过滤器?
类似于使用a findFirst或findAny作为终端操作的东西:
Optional<A> matchingObject = aList.stream()
.filter(a -> a.getbSet().contains(b))
.findFirst();
Run Code Online (Sandbox Code Playgroud)