Possible Duplicate:
Java: Detect duplicates in ArrayList?
To check if a List has duplicate entries i convert it to HashSet and compare the size for any mismatch. Do you guys have any better approach?
This code may break somewhat earlier if you have duplicates at the beginning of the collection:
HashSet<Integer> hashSet = new HashSet<>();
for(Integer i : myList) {
if(!hashSet.add(i)) return true;
}
As Pshemo pointed out, the add
method returns a bool
whether an element has actually been added to the collection, as opposed to has already existed in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With