1. Introduction

An ArrayList in Java can hold duplicate elements. However, there might be scenarios where we are required to obtain a list containing only the unique elements. This guide demonstrates how to extract unique elements from an ArrayList using a Set.

2. Program Steps

1. Initialize an ArrayList and add elements to it.

2. Convert the ArrayList to a Set to remove duplicate elements.

3. (Optional) Convert the Set back to an ArrayList if needed.

4. Display the unique elements.

3. Code Program

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

public class UniqueArrayList {

    public static void main(String[] args) {

        // Step 1: Initialize an ArrayList and add elements to it
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(2);
        numbers.add(4);
        numbers.add(3);

        // Step 2: Convert the ArrayList to a Set to remove duplicate elements
        Set<Integer> uniqueNumbers = new HashSet<>(numbers);

        // Step 3: (Optional) Convert the Set back to an ArrayList if needed
        ArrayList<Integer> uniqueNumbersList = new ArrayList<>(uniqueNumbers);

        // Step 4: Display the unique elements
        System.out.println("Original ArrayList: " + numbers);
        System.out.println("Unique Elements: " + uniqueNumbersList);
    }
}

Output:

Original ArrayList: [1, 2, 3, 2, 4, 3]
Unique Elements: [1, 2, 3, 4]

4. Step By Step Explanation

Step 1: An ArrayList named numbers is initialized and populated with both unique and duplicate Integer elements.

Step 2: The ArrayList is converted to a HashSet named uniqueNumbers. A HashSet is a collection of elements where every element is unique, thus automatically removing any duplicate values.

Step 3: Optionally, if you need the result in ArrayList form, the HashSet can be converted back to an ArrayList named uniqueNumbersList.

Step 4: Both the original ArrayList and the list of unique elements are printed to the console, showing the removal of duplicate values.