[英]How should I get the difference between 2 list<Object>
有2个具有不同大小和对象的实体列表,例如List<BrandEntity> baseEntityList
和List<BrandEntity> subEntityList
,现在我想获取存储在baseEntityList中而不是subEntityList中的结果,不同的维度是brandName。 我已经覆盖了equals方法,但是它不起作用。 这是我的代码。
Main.class:
findDifferenceList(baseEntityList, subEntityList)
Method:
private <T> List<T> findDifferenceList(List<T> baseBrandList, List<T> subBrandList) {
return baseBrandList.stream().filter(item -> !subBrandList.contains(item)).collect(toList());
}
BrandEntity:
@Slf4j
public class BrandEntity {
@JsonSetter("shopid")
Long shopId;
@JsonSetter("brand")
String brandName;
@JsonIgnore Long principalId;
// getter and setter
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BrandEntity that = (BrandEntity) o;
return Objects.equals(brandName, that.brandName);
}
@Override
public int hashCode() {
return Objects.hash(brandName);
}
}
这是一些棘手的代码,如果我想这样做,我会删除所有subEntityList
从baseEntityList
或者如果您想在两个列表中找到差异,可以对两个列表都进行
var diffWithBase = subEntityList.removeAll(baseEntityList);
var diffWithSubList = baseEntityList.removeAll(subEntityList);
// print
您可以尝试使用老式Java方法
List<BrandEntity> diff = new ArrayList<>(baseEntityList);
difference.removeAll(subEntityList);
return diff;
List<BrandEntity> findDifferenceList(List<BrandEntity> list1, List<BrandEntity> list2) {
return list1.stream().filter(i -> !list2.contains(i))
.concat(list2.stream.filter(i -> !list1.contains(i))
.collect(Collectors.toList());
}
您需要按照两个方向进行操作;)。 A和B中没有什么,B和A中没有什么。
好了,您正在做的是根据字符串的引用相等性比较字符串-如下面的Objects中所示。 但是您需要在它们的值相等brandName.equals(that.brandName)
例如brandName.equals(that.brandName)
上进行比较。
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
尽管如此,我还是希望使用现有的库来比较List,例如Apache的共同点CollectionUtils
:
CollectionUtils.removeAll(List<T> baseBrandList, List<T> subBrandList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.