-4

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

charkoul
  • 67
  • 1
  • 9

1 Answers1

3

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());
xenteros
  • 15,586
  • 12
  • 56
  • 91