如果你想实现equals 和hashCode,可以在在类Parent 中实现。在该类中添加方法,如
@Override
public int hashCode() {
return Objects.hash(getAttrib1(), getAttrib2(), getAttrib3(),
// …
getAttrib19(), getAttrib20());
}
@Override
public boolean equals(Object obj) {
if(this==obj) return true;
if(!(obj instanceof Parent)) return false;
Parent p=(Parent) obj;
return Objects.equals(getAttrib1(), p.getAttrib1())
&& Objects.equals(getAttrib2(), p.getAttrib2())
&& Objects.equals(getAttrib3(), p.getAttrib3())
// …
&& Objects.equals(getAttrib19(), p.getAttrib19())
&& Objects.equals(getAttrib20(), p.getAttrib20());
}
如果您这样做了,在 Stream<Parent> 上调用的 distinct() 将自动执行正确的操作。
如果您不想(或不能)更改类 Parent,则没有相等的委托机制,但您可以诉诸 ordering,因为它具有委托机制:
Comparator<Parent> c=Comparator.comparing(Parent::getAttrib1)
.thenComparing(Parent::getAttrib2)
.thenComparing(Parent::getAttrib3)
// …
.thenComparing(Parent::getAttrib19)
.thenComparing(Parent::getAttrib20);
这定义了基于属性的顺序。它要求属性本身的类型具有可比性。如果你有这样的定义,你可以用它来实现一个distinct()的等价物,基于那个Comparator:
List<Parent> result = Stream.concat(list1.stream(), list2.stream())
.filter(new TreeSet<>(c)::add)
.collect(Collectors.toList());
还有一个线程安全的变体,以防您想将它与并行流一起使用:
List<Parent> result = Stream.concat(list1.stream(), list2.stream())
.filter(new ConcurrentSkipListSet<>(c)::add)
.collect(Collectors.toList());