【问题标题】:Remove duplicate Tuples from an ArrayList- Java从 ArrayList-Java 中删除重复的元组
【发布时间】:2020-02-24 19:38:36
【问题描述】:

我想要一个没有重复的唯一元组列表。

List <Tuple>  newNonZeros = new ArrayList<>(); 

newNonZeroes 中的结果是:[(0,2)(1,2)(1,2)(1,1)(2,2)(2,2)(2,1)]

这是我尝试过的:

List <Tuple> newList = new ArrayList<>();
newList.add(newNonZeros.get(0));

for(int i=1; i < newNonZeros.size();i++){
    if(newNonZeros.get(i-1)!= newNonZeros.get(i)){
        newList.add(newNonZeros.get(i));
    }
}

它不起作用。谁能帮帮我...这是一个非常简单的问题

我也尝试了以下方法:

...newNonZeros.stream().distinct().collect(Collectors.toList());

【问题讨论】:

  • List newNonZeros = new ArrayList();*
  • 删除重复元素让我想到了集合
  • != 检查引用相等而不是数据相等。您需要改用equals()

标签: java arraylist duplicates redundancy


【解决方案1】:

Tuple 类中覆盖 equalshashCode

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Tuple tuple = (Tuple) o;
    return first == tuple.first &&
            second == tuple.second;
}

@Override
public int hashCode() {
    return Objects.hash(first, second);
}

那么你可以使用:

List<Tuple> newList = newNonZeros.stream()
                               .distinct()
                               .collect(Collectors.toList());

或者使用 for-each 循环:

List<Tuple> newList = new ArrayList<>();
for(Tuple tuple : newNonZeros) {
    if(!newList.contains(tuple)) {
        newList.add(tuple);
    }
}

【讨论】:

  • 谢谢你的朋友=)
猜你喜欢
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 2016-07-23
  • 2010-10-13
  • 2011-01-26
  • 2012-08-25
  • 1970-01-01
相关资源
最近更新 更多