我正在寻找一种简洁有效的方法来使用 Java 8 流从子列表中获取唯一父列表。
对于这个例子,我有这两个简单的类:
public class Child{
private Parent parent;
public Child(Parent parent){
this.parent = parent;
}
public Parent getParent(){
return this.parent;
}
}
public class Parent{
private List<Child> children;
public Parent(){
this.children = new ArrayList<Child>();
}
public void addChild(Child child){
this.children.add(child);
}
}
首先,我从某种方法获取 Child 对象的列表。
child 可能属于多个 parent ,可能会发生 parent 冲突。
List<Child> children = getChildren();
然后:
List<Parent> uniqueParents = children
.stream()
.collect(Collectors.groupingBy(Child::getParent))
.keySet()
.stream()
.collect(Collectors.toList());
所以它有效,但我想避免双流和收集。
这可以直接在一个流中吗?
最佳答案
这个怎么样:
List<Parent> uniqueParents = children
.stream()
.map(Child::getParent)
.distinct()
.collect(Collectors.toList());
关于java - 流分组: children list to unique parent list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34158383/