Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check duplicate entries in a List [duplicate]

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?

like image 615
Farrukh Chishti Avatar asked Dec 19 '12 09:12

Farrukh Chishti


1 Answers

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.

like image 159
Matthias Meid Avatar answered Sep 30 '22 07:09

Matthias Meid