【发布时间】:2016-07-11 21:58:55
【问题描述】:
我需要将 listB 的所有元素合并到另一个列表 listA 中。
如果 listA 中已经存在一个元素(基于自定义相等检查),我不想添加它。
我不想使用 Set,也不想重写 equals() 和 hashCode()。
原因是,我不想防止 listA 本身出现重复,我只想在 listA 中已经存在我认为相等的元素时不从 listB 合并。
我不想覆盖 equals() 和 hashCode(),因为这意味着我需要确保我对元素的 equals() 实现在任何情况下都适用。然而,listB 中的元素可能没有完全初始化,即它们可能会丢失一个对象 id,而该对象 id 可能存在于 listA 的元素中。
我目前的方法涉及一个接口和一个实用程序功能:
public interface HasEqualityFunction<T> {
public boolean hasEqualData(T other);
}
public class AppleVariety implements HasEqualityFunction<AppleVariety> {
private String manufacturerName;
private String varietyName;
@Override
public boolean hasEqualData(AppleVariety other) {
return (this.manufacturerName.equals(other.getManufacturerName())
&& this.varietyName.equals(other.getVarietyName()));
}
// ... getter-Methods here
}
public class CollectionUtils {
public static <T extends HasEqualityFunction> void merge(
List<T> listA,
List<T> listB) {
if (listB.isEmpty()) {
return;
}
Predicate<T> exists
= (T x) -> {
return listA.stream().noneMatch(
x::hasEqualData);
};
listA.addAll(listB.stream()
.filter(exists)
.collect(Collectors.toList())
);
}
}
然后我会这样使用它:
...
List<AppleVariety> appleVarietiesFromOnePlace = ... init here with some elements
List<AppleVariety> appleVarietiesFromAnotherPlace = ... init here with some elements
CollectionUtils.merge(appleVarietiesFromOnePlace, appleVarietiesFromAnotherPlace);
...
在 listA 中获取我的新列表,其中所有元素都从 B 合并。
这是一个好方法吗?有没有更好/更简单的方法来完成同样的事情?
【问题讨论】:
标签: java collections java-8 java-stream