</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to remove duplicate elements from an ArrayList using HashSet.

Answer

Remove Duplicates from ArrayList Using HashSet

Java
import java.util.ArrayList;
import java.util.HashSet;

public class RemoveDuplicatesFromArrayList {
    public static void main(String[] args) {

        // Constructing An ArrayList with duplicate elements
        ArrayList listWithDuplicateElements = new ArrayList();

        listWithDuplicateElements.add("JAVA");
        listWithDuplicateElements.add("J2EE");
        listWithDuplicateElements.add("JSP");
        listWithDuplicateElements.add("SERVLETS");
        listWithDuplicateElements.add("JAVA");      // duplicate
        listWithDuplicateElements.add("STRUTS");
        listWithDuplicateElements.add("JSP");       // duplicate

        // Printing listWithDuplicateElements
        System.out.print("ArrayList With Duplicate Elements: ");
        System.out.println(listWithDuplicateElements);

        // Constructing HashSet from ArrayList (removes duplicates)
        HashSet set = new HashSet(listWithDuplicateElements);

        // Constructing listWithoutDuplicateElements using set
        ArrayList listWithoutDuplicateElements = new ArrayList(set);

        // Printing listWithoutDuplicateElements
        System.out.print("ArrayList After Removing Duplicate Elements: ");
        System.out.println(listWithoutDuplicateElements);
    }
}

Output

CODE
ArrayList With Duplicate Elements: [JAVA, J2EE, JSP, SERVLETS, JAVA, STRUTS, JSP]
ArrayList After Removing Duplicate Elements: [JAVA, J2EE, STRUTS, SERVLETS, JSP]

Preserve Insertion Order → Use LinkedHashSet

Java
import java.util.LinkedHashSet;

ArrayList<String> list = new ArrayList<>();
list.add("JAVA"); list.add("J2EE"); list.add("JSP");
list.add("SERVLETS"); list.add("JAVA"); list.add("STRUTS"); list.add("JSP");

// LinkedHashSet preserves order + removes duplicates
LinkedHashSet<String> set = new LinkedHashSet<>(list);
ArrayList<String> result  = new ArrayList<>(set);

System.out.println(result);
// → [JAVA, J2EE, JSP, SERVLETS, STRUTS]  (order preserved)

HashSet vs LinkedHashSet vs TreeSet

HashSetLinkedHashSetTreeSet
DuplicatesNot allowedNot allowedNot allowed
OrderNo orderInsertion orderSorted order
Null allowedOne nullOne nullNo null
PerformanceO(1)O(1)O(log n)
Use whenJust remove dupsRemove + preserve orderRemove + sort

Automation Testing Relevance

Java
// Remove duplicate window handles
Set<String> handles = driver.getWindowHandles();
// getWindowHandles() already returns a Set (no duplicates)

// Remove duplicate element texts from a list
List<WebElement> items = driver.findElements(By.css(".tag"));
List<String> texts = items.stream().map(WebElement::getText).collect(Collectors.toList());
ArrayList<String> uniqueTexts = new ArrayList<>(new LinkedHashSet<>(texts));
System.out.println("Unique tags: " + uniqueTexts);

Follow AutomateQA