Remove duplicates from a Java List [duplicate]

做~自己de王妃 提交于 2020-01-24 01:59:10

问题


I want to remove duplicates from a list like bellow

List<DataRecord> transactionList =new ArrayList<DataRecord>();

where the DataRecord is a class

public class DataRecord {
    [.....]
    private String TUN; 

and the TUN should be unique


回答1:


There are two possbile solutions.

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));

When you can't override the equals method, you need to find a workaround. My idea is the following:

  1. Create a helper HashMap<String, DataRecord> where keys will be TUNs.
  2. Create an ArrayList out of values() set.

Implementation:

Map<String, DataRecord> helper = new HashMap<>();
for (DataRecord dr : transactionList) {
    helper.putIfAbsent(dr.getTUN(), dr);
}
List<DataRecord> noDuplicatesList = new ArrayList<>(helper.values());


来源:https://stackoverflow.com/questions/59594433/remove-duplicates-from-a-java-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!