How to find duplicate in an array Java? One of the most frequently asked questions on the technical interview. And one of the most straightforward solutions. The only thing you need to do is to convert an array list to the set. And point the element that we can’t add. Why? Because the set collection contains just unique values.
How to find the duplicate in an Array List (Java)? Step-by-step implementation.
The easiest solution below:
- Set the “result” variable that we will assign to a value after we find the duplicate;
//Defining the result variable
int result = 0;
- Iterate each element of the array and add each element in the set;
//Looping through the array
for (int i : array)
- If we can’t add the element, that means the value already exists in the set. And the operation will return falls. That means we have found the duplicate;
//If set can't add item that means the item already exists
if (!lump.add(i)) {
result = i;
}
Full code solution:
private void findDuplicateInArray() {
//Creating array of integers
int[] array = new int[]{1, 8, 3, 4, 2, 5, 1};
//Defining the result variable
int result = 0;
//Using set since set don't allow duplicates
Set<Integer> lump = new HashSet<Integer>();
//Looping through the array
for (int i : array) {
//If set can't add item that means the item already exists
if (!lump.add(i)) {
result = i;
}
}
//Showing the result
Log.d("arrayList", "result -> " + result);
}
Full schema:

In this article, I show you the solution to find duplicate in array list (Java).
Full code and more examples in my facebook group.
Useful links:
Leave Any Questions Related To This Article Below!