我的情况类似于:
public class A {
private String id;
@ManyToMany
private Set<B> bSet;
// getters and setters
}
和
public class B {
private String id;
// other attributes
// getters and setters
}
使用A
API拥有B
实例时,如何找到stream()
实例?我正在尝试类似的东西:
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();
}
如何正确编写此过滤器?
答案 0 :(得分:5)
类似使用findFirst
或findAny
作为终端操作的事情:
Optional<A> matchingObject = aList.stream()
.filter(a -> a.getbSet().contains(b))
.findFirst();