首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从对象的arrayList中删除重复行,但在不同列中具有重复行项目

从对象的arrayList中删除重复行,但在不同列中具有重复行项目
EN

Stack Overflow用户
提问于 2018-05-15 03:32:24
回答 4查看 58关注 0票数 0

我有一个类型为

Couple(String person1, String person2)

以及一个具有多个成对类型的项的ArrayList<Couple> relationshipList = new ArrayList<Couple>();,其中所有成对对象在列表中复制一次。例如,这是我的示例arrayList:

代码语言:javascript
复制
relationshipList.add(new Couple("John", "Amy"));
relationshipList.add(new Couple("Eliot", "Megan"));
relationshipList.add(new Couple("Billy", "Rachel"));
relationshipList.add(new Couple("Amy", "John"));
relationshipList.add(new Couple("Jim", "Kate"));
relationshipList.add(new Couple("Kate", "Jim"));
relationshipList.add(new Couple("Megan", "Eliot"));
relationshipList.add(new Couple("Rachel", "Billy"));

我正在尝试找到一种方法来删除重复的情侣,因为在这个例子中,John和艾米是同一对情侣,在列表中添加了两次,只是在列中交换了他们的名字。(假设在这个场景中不存在两个同名的人,而John只提到"John和艾米“这对情侣),有人能帮我吗?

EN

回答 4

Stack Overflow用户

发布于 2018-05-15 03:37:41

你可以

  1. 重写equals()方法,以便根据需要比较对象。然后

relationshipList.stream().distinct().collect(Collectors.asList());

  • make自定义筛选器类,它保存遇到的值的映射。然后

relationshipList.stream().filter(yourFilter::compare).collect(Collectors.asList());

票数 0
EN

Stack Overflow用户

发布于 2018-05-15 03:47:58

您首先需要为耦合实现equals方法,如下所示

PS:您还可以将null检查

代码语言:javascript
复制
public boolean equals(Object otherCouple){
  if(otherCouple != null && otherCouple instanceof Couple){
    return (this.person1.equals(otherCouple.getPerson1())
        && this.person2.equals(otherCouple.getPerson2()))
        || (this.person1.equals(otherCouple.getPerson2())
        && this.person2.equals(otherCouple.getPerson1()))

  }
  return false;
}

然后,您只需将每一对添加到Set<Couple>中,所有重复项都将被删除。

票数 0
EN

Stack Overflow用户

发布于 2018-05-15 03:56:25

最基本的问题是重复项,只有一个数据结构可以保证删除重复项:集合。

为了利用sets,您必须在Couple类中提供equalshashCode的实现。

为了确定相等性,您需要验证大约两种状态(如果对象实际上是一个Couple,则需要验证):

  • this.person1 == other.person1 && this.person2 == other.person2
  • this.person2 == other.person1 && this.person1 == other.person2

您可以将它们表示为Objects.equals(this.person1, other.person1) && Objects.equals(this.person2, other.person2),但是完整地编写出来对读者来说是一个练习。

至于散列码,您可以使用Objects.hashCode为您获取该值。

代码语言:javascript
复制
@Override
public int hashCode() {
    return Objects.hashCode(person1, person2);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50337733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档