Java 8 Stream-如何从子级找到父级实体? [英] Java 8 stream - how to find parent entity from child?
本文介绍了Java 8 Stream-如何从子级找到父级实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的情况类似于:
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
}
当使用stream()
API拥有B
的实例时,如何找到A
的实例?我正在尝试类似的东西:
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?
推荐答案
类似使用findFirst
或findAny
作为终端操作的事情:
Soemthing like using a findFirst
or findAny
as a terminal operation:
Optional<A> matchingObject = aList.stream()
.filter(a -> a.getbSet().contains(b))
.findFirst();
这篇关于Java 8 Stream-如何从子级找到父级实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文