我有一个具有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 11:55:38
覆盖Parent
类中的equals
和hashCode
方法,以避免列表中的重复项。这将为您提供您想要的确切结果。
发布于 2015-06-16 12: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 11:55:48
如果要覆盖.equals(…)
和.hashCode()
,则需要在Parent
类上执行此操作。请注意,这可能会导致Parent
的其他使用失败。Alexis C.的链接解决方案更为保守。
https://stackoverflow.com/questions/30866753
复制相似问题