我有一个具有20个属性(attrib1, attrib2 .. attrib20)及其对应的getter和setter的Parent类。我还有两个Parent对象列表:list1和list2。
现在我想合并这两个列表,并避免基于attrib1和attrib2的重复对象。
使用Java 8:
List<Parent> result = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList()); 但是我必须在哪个地方指定属性呢?我应该重写hashCode和equals方法吗?
发布于 2015-06-16 19:55:38
覆盖Parent类中的equals和hashCode方法,以避免列表中的重复项。这将为您提供您想要的确切结果。
发布于 2015-06-16 20:19:57
例如:
public class Parent {
public int no;
public String name;
@Override
public int hashCode() {
return (no << 4) ^ name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Parent))
return false;
Parent o = (Parent)obj;
return this.no == o.no && this.name.equals(o.name);
}
}发布于 2015-06-16 19:55:48
如果要覆盖.equals(…)和.hashCode(),则需要在Parent类上执行此操作。请注意,这可能会导致Parent的其他使用失败。Alexis C.的链接解决方案更为保守。
https://stackoverflow.com/questions/30866753
复制相似问题