有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:@Slf4jpublic 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); }}
4 回答

四季花海
// print
TA貢獻1811條經驗 獲得超5個贊
subEntityList這是一些棘手的代碼,如果我想這樣做,我會從中刪除所有代碼baseEntityList
,或者如果你想在兩個列表中找到差異,你可以為他們兩個做
var diffWithBase = subEntityList.removeAll(baseEntityList);
var diffWithSubList = baseEntityList.removeAll(subEntityList);

慕后森
TA貢獻1802條經驗 獲得超5個贊
你可以嘗試oldschool Java方式
List<BrandEntity> diff = new ArrayList<>(baseEntityList);
difference.removeAll(subEntityList);
return diff;

慕田峪9158850
TA貢獻1794條經驗 獲得超7個贊
那么你正在做的是根據它們的引用相等性來比較字符串 - 如對象(如下)中所示。但是您需要比較它們的價值是否相等,例如brandName.equals(that.brandName)
。
public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); }
盡管如此,我寧愿使用現有的庫來比較列表,例如 Apache 的 commons CollectionUtils
:
CollectionUtils.removeAll(List<T> baseBrandList, List<T> subBrandList);

鳳凰求蠱
TA貢獻1825條經驗 獲得超4個贊
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 中。
添加回答
舉報
0/150
提交
取消