Java - How to Remove Duplicates in ArrayList Based on Multiple Properties

posed1940 :

I want to remove duplicate records from an arraylist based on multiple properties. This is a sample domain object class:

private String mdl;
private String ndc;
private String gpi;
private String labelName;
private int seqNo;
private String vendorName;

The mdl, ndc, gpi, and seqNo together make up a unique record. I want to find duplicates in an arraylist that checks for these 4 properties and then removes the record from the list if a record with the same 4 properties already exists in the list.

buræquete :

You can try doing the following;

List<Obj> list = ...; // list contains multiple objects
Collection<Obj> nonDuplicateCollection = list.stream()
        .collect(Collectors.toMap(Obj::generateUniqueKey, Function.identity(), (a, b) -> a))
        .values();

(a, b) -> a, means that when two objects are identical, the final map will contain the earlier object, the latter one will be discarded, you can change this behaviour if you'd like the latter one.

where Obj is;

public static class Obj {

    private String mdl;
    private String ndc;
    private String gpi;
    private String labelName;
    private int seqNo;
    private String vendorName;

    // other getter/setters

    public String generateUniqueKey() {
        return mdl + ndc + gpi + seqNo;
    }
}

I'd rather do something like this, than to override hashCode or equals methods, which might be necessary in another logic in their default states... Plus explicitly showing how you are asserting the uniqueness with a proper method like generateUniqueKey is better than hiding that logic in some hashCode method is much better in terms of readability & maintainability.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127909&siteId=1