[Solved] Remove duplicates from a Java List [duplicate]


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

3

solved Remove duplicates from a Java List [duplicate]