我应该如何获得 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);

  }

}


隔江千里
浏览 144回答 4
4回答

四季花海

subEntityList这是一些棘手的代码,如果我想这样做,我会从中删除所有代码baseEntityList,或者如果你想在两个列表中找到差异,你可以为他们两个做var diffWithBase = subEntityList.removeAll(baseEntityList);var diffWithSubList = baseEntityList.removeAll(subEntityList);// print&nbsp;

慕后森

你可以尝试oldschool Java方式List<BrandEntity> diff = new ArrayList<>(baseEntityList);difference.removeAll(subEntityList);return diff;

慕田峪9158850

那么你正在做的是根据它们的引用相等性来比较字符串 - 如对象(如下)中所示。但是您需要比较它们的价值是否相等,例如brandName.equals(that.brandName)。public&nbsp;static&nbsp;boolean&nbsp;equals(Object&nbsp;a,&nbsp;Object&nbsp;b)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;(a&nbsp;==&nbsp;b)&nbsp;||&nbsp;(a&nbsp;!=&nbsp;null&nbsp;&&&nbsp;a.equals(b)); }尽管如此,我宁愿使用现有的库来比较列表,例如 Apache 的 commons&nbsp;CollectionUtils:CollectionUtils.removeAll(List<T>&nbsp;baseBrandList,&nbsp;List<T>&nbsp;subBrandList);

凤凰求蛊

List<BrandEntity>&nbsp;findDifferenceList(List<BrandEntity>&nbsp;list1,&nbsp;List<BrandEntity>&nbsp;list2)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;list1.stream().filter(i&nbsp;->&nbsp;!list2.contains(i)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.concat(list2.stream.filter(i&nbsp;->&nbsp;!list1.contains(i)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList()); }你需要做你在两个方向上所做的事情;)。什么不在 A 和 B 中,什么不在 B 和 A 中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java