从 Java 列表中删除重复项 [英] Remove duplicates from a Java List
本文介绍了从 Java 列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从如下列表中删除重复项
I want to remove duplicates from a list like bellow
List<DataRecord> transactionList =new ArrayList<DataRecord>();
DataRecord 是一个类
where the DataRecord is a class
public class DataRecord {
[.....]
private String TUN;
并且 TUN 应该是唯一的
and the TUN should be unique
推荐答案
有两种可能的解决方案.
There are two possbile solutions.
第一个是覆盖equals方法.只需添加:
The first one is to override the equals method. Simply add:
public class DataRecord {
[.....]
private String TUN;
@Override
public boolean equals(Object o) {
if (o instanceof DataRecord) {
DataRecord that = (DataRecord) o;
return Objects.equals(this.TUN, that.TUN);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(TUN);
}
}
然后,以下代码将删除重复项:
Then, the follwing code will remove duplicates:
List<DataRecord> noDuplicatesList = new ArrayList<>(new HashSet<>(transactionList));
当您无法覆盖equals方法时,您需要找到解决方法.我的想法如下:
When you can't override the equals method, you need to find a workaround. My idea is the following:
- 创建一个帮助程序
HashMap
,其中的键是 TUN. - 从
values()
集合中创建一个ArrayList
.
- Create a helper
HashMap<String, DataRecord>
where keys will be TUNs. - Create an
ArrayList
out ofvalues()
set.
实施:
Map<String, DataRecord> helper = new HashMap<>();
for (DataRecord dr : transactionList) {
helper.putIfAbsent(dr.getTUN(), dr);
}
List<DataRecord> noDuplicatesList = new ArrayList<>(helper.values());
这篇关于从 Java 列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文