【发布时间】:2017-02-20 20:34:08
【问题描述】:
我有一个 Thingy pojo 的列表,例如:
public class Thingy {
private DifferentThingy nestedThingy;
public DifferentThingy getNestedThingy() {
return this.nestedThingy;
}
}
...
public class DifferentThingy {
private String attr;
public String getAttr() {
return this.attr;
}
}
我要过滤一个
List<Thingy>
是唯一的基于
attr
Thingy 的
DifferentThingy
这是我迄今为止尝试过的:
private List<Thingy> getUniqueBasedOnDifferentThingyAttr(List<Thingy> originalList) {
List<Thingy> uniqueItems = new ArrayList<Thingy>();
Set<String> encounteredNestedDiffThingyAttrs= new HashSet<String>();
for (Thingy t: originalList) {
String nestedDiffThingyAttr = t.getNestedThingy().getAttr();
if(!encounteredNestedDiffThingyAttrs.contains(nestedDiffThingyAttr)) {
encounteredNestedDiffThingyAttrs.add(nestedDiffThingyAttr);
uniqueItems.add(t);
}
}
return uniqueItems;
}
我想为最终检索用于确定唯一性的属性的两个 getter 使用 Java 8 流和 lambda,但我不确定如何。当用于比较的属性位于 pojo 的顶层时,我知道该怎么做,但当属性嵌套在另一个对象中时,我不知道。
【问题讨论】:
标签: java lambda java-8 java-stream