.equals()
and .hashCode()
should be overridden to account for your key: mdl, ndc. gpi, seqNo. There are countless guides to doing this on this site, but something like:
@Override
public boolean equals(Object obj) {
if(obj != null && obj instanceof MyClass) {
MyClass o = (MyClass)obj;
return mdl.equals(o.mdl) && ndc.equals(o.ndc) &&
gpi.equals(o.gpi) && seqNo == o.seqNo;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(mdl, ndc, gpi, seqNo);
}
There may be more efficient ways of implementing them if that's a concern.
Then you can just convert your list to a set with:
Set<MyClass> set = new HashSet<>(list);
The resulting set
won't have any duplicates and you can now replace your list with the new values list = new ArrayList<>(set);
if you need to.
If you want to maintain the order of the items in the original list, instantiate LinkedHashSet
instead of HashSet
.
Unrelated to your direct question, perhaps consider using a Set
instead of List
if you want to avoid duplicates in the first place. It will make your code more efficient (less memory usage without the duplicates) and eliminate the need to search for duplicates afterwards.