从对象的arrayList中删除重复的行,但在不同的列中包含重复的行项

时间:2018-05-14 19:32:24

标签: java arraylist

我有一个

类型的对象

Couple(String person1, String person2)

ArrayList<Couple> relationshipList = new ArrayList<Couple>();具有各种类型的Couple类型,其中所有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和Amy是同一对夫妇在列表中添加两次,只是他们的名字在列中交换。(假设有两个人在这种情况下不存在相同的名称,约翰只提到“约翰和艾米”情侣。任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:0)

你可以

  1. 覆盖equals()方法,根据需要比较对象。然后

    relationshipList.stream().distinct().collect(Collectors.asList());
    
  2. 创建一个自定义过滤器类,其中包含遇到值的映射。然后

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

答案 1 :(得分:0)

你首先需要为下面的夫妇实现equals方法

PS:您还可以进行空检查

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>,所有重复项都将被移除。

答案 2 :(得分:0)

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

为了利用集合,您必须在{{1}中提供 equals hashCode 的实施} class。

要确定相等性,您需要验证两种状态(如果对象实际上是Couple之外):

  • 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

答案 3 :(得分:0)

如果你不能覆盖equals / hashCode并且你愿意使用java-8并且你愿意添加一个实用工具方法,取自Stuart Mark's answer

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}

这可以通过以下方式完成:

relationshipList.stream()
            .map(x -> new SimpleEntry<>(x,
                    Stream.of(x.getPerson1(), x.getPerson2()).sorted().collect(Collectors.joining())))
            .filter(distinctByKey(Entry::getValue))
            .map(Entry::getKey)
            .collect(Collectors.toList())
相关问题