从Java列表中删除重复项 [英] Remove duplicates from a Java List

查看:84
本文介绍了从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:

  1. 创建一个帮助键HashMap<String, DataRecord>,其中的键将是TUN.
  2. values()集中创建一个ArrayList.
  1. Create a helper HashMap<String, DataRecord> where keys will be TUNs.
  2. Create an ArrayList out of values() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆