How to Remove All Duplicates from an ArrayList – Java Collections | Java Program Interview Question

One of the commonly asked Java Interview Questions is how to remove all duplicates from an ArrayList. We will use Set to remove the duplicate values and then pass that HashSet to the ArrayList without duplicate values.

Step 1:

Initialized the ArrayList with duplicate values

Step 2:

Initialized the Set and passed duplicate values in the HashSet constructor

Step 3:

Initialized one more ArrayList without duplicates and passed the Set in the ArrayList constructor

Example – Remove all duplicates from ArrayList:

package TestAutomationCentral;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicatesArrayList {
    public static void main(String[] args) {
        //TestAutomationCentral.com
        List<String> duplicateList = new ArrayList<>();
        duplicateList.add("One");
        duplicateList.add("One");
        duplicateList.add("Two");
        duplicateList.add("Two");
        duplicateList.add("Three");

        System.out.println("List with Duplicate - " + duplicateList);
        Set<String> set = new HashSet<>(duplicateList);
        List<String> withoutDuplicateList = new ArrayList<>(set);
        System.out.println("List without Duplicate - " + withoutDuplicateList);

    }
}

Output:

List with Duplicate – [One, One, Two, Two, Three]
List without Duplicate – [One, Two, Three]

Share

Leave a Reply