How to find duplicate in an Array List Java? • IT Blog
IT Blog
Boris IT Expert

How to find duplicate in an Array List Java?

Boris~November 9, 2020 /Array List

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:

//Defining the result variable
        int result = 0;
//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;
            }

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:

find duplicate in array list

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!