我有一个类型为
Couple(String person1, String person2),
以及一个具有多个成对类型的项的ArrayList<Couple> relationshipList = new ArrayList<Couple>();,其中所有成对对象在列表中复制一次。例如,这是我的示例arrayList:
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和艾米“这对情侣),有人能帮我吗?
发布于 2018-05-15 03:37:41
你可以
equals()方法,以便根据需要比较对象。然后relationshipList.stream().distinct().collect(Collectors.asList());
relationshipList.stream().filter(yourFilter::compare).collect(Collectors.asList());
发布于 2018-05-15 03:47:58
您首先需要为耦合实现equals方法,如下所示
PS:您还可以将null检查
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>中,所有重复项都将被删除。
发布于 2018-05-15 03:56:25
最基本的问题是重复项,只有一个数据结构可以保证删除重复项:集合。
为了利用sets,您必须在Couple类中提供equals和hashCode的实现。
为了确定相等性,您需要验证大约两种状态(如果对象实际上是一个Couple,则需要验证):
this.person1 == other.person1 && this.person2 == other.person2this.person2 == other.person1 && this.person1 == other.person2您可以将它们表示为Objects.equals(this.person1, other.person1) && Objects.equals(this.person2, other.person2),但是完整地编写出来对读者来说是一个练习。
至于散列码,您可以使用Objects.hashCode为您获取该值。
@Override
public int hashCode() {
return Objects.hashCode(person1, person2);
}https://stackoverflow.com/questions/50337733
复制相似问题