0
0
JavaHow-ToBeginner · 2 min read

Java How to Convert ArrayList to HashSet Easily

You can convert an ArrayList to a HashSet in Java by passing the ArrayList to the HashSet constructor like this: HashSet set = new HashSet<>(arrayList);.
📋

Examples

Input["apple", "banana", "apple"]
Output["apple", "banana"]
Input[1, 2, 3, 2, 4]
Output[1, 2, 3, 4]
Input[]
Output[]
🧠

How to Think About It

To convert an ArrayList to a HashSet, think of it as putting all the items from a list into a set container that automatically removes duplicates. You just create a new HashSet and give it the ArrayList, so it copies all unique items.
📐

Algorithm

1
Get the input ArrayList.
2
Create a new empty HashSet.
3
Add all elements from the ArrayList to the HashSet.
4
Return or use the HashSet which now contains unique elements.
💻

Code

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

public class ConvertListToSet {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("apple");

        HashSet<String> fruitSet = new HashSet<>(fruits);
        System.out.println(fruitSet);
    }
}
Output
[banana, apple]
🔍

Dry Run

Let's trace converting ["apple", "banana", "apple"] from ArrayList to HashSet.

1

Start with ArrayList

ArrayList contains ["apple", "banana", "apple"]

2

Create HashSet from ArrayList

HashSet now contains unique elements from ArrayList: ["apple", "banana"]

3

Print HashSet

Output is [banana, apple] (order may vary)

StepArrayListHashSet
1[apple, banana, apple][]
2[apple, banana, apple][apple, banana]
3[apple, banana, apple][banana, apple]
💡

Why This Works

Step 1: HashSet removes duplicates

When you create a HashSet from an ArrayList, it automatically removes duplicate elements because sets only keep unique items.

Step 2: Constructor copies elements

The HashSet constructor takes the ArrayList and copies all its elements into the set.

Step 3: Order is not guaranteed

HashSet does not keep the order of elements, so the output order may differ from the original list.

🔄

Alternative Approaches

Using addAll() method
java
import java.util.ArrayList;
import java.util.HashSet;

public class ConvertListToSetAlt {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("apple");

        HashSet<String> fruitSet = new HashSet<>();
        fruitSet.addAll(fruits);
        System.out.println(fruitSet);
    }
}
This method creates an empty HashSet first and then adds all elements from the ArrayList. It is more flexible if you want to add elements conditionally.
Using Java Streams (Java 8+)
java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.stream.Collectors;

public class ConvertListToSetStream {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("apple");

        HashSet<String> fruitSet = fruits.stream()
            .collect(Collectors.toCollection(HashSet::new));
        System.out.println(fruitSet);
    }
}
This approach uses streams to convert the list to a set, which is useful for more complex processing or filtering before collecting.

Complexity: O(n) time, O(n) space

Time Complexity

Copying all elements from the ArrayList to the HashSet takes O(n) time because each element is processed once.

Space Complexity

The HashSet stores unique elements, so it requires O(n) space in the worst case when all elements are unique.

Which Approach is Fastest?

Using the HashSet constructor or addAll() method both have similar performance. Streams add slight overhead but offer more flexibility.

ApproachTimeSpaceBest For
HashSet constructorO(n)O(n)Simple and fast conversion
addAll() methodO(n)O(n)When you want to add conditionally or incrementally
StreamsO(n)O(n)When processing/filtering before conversion
💡
Use the HashSet constructor with the ArrayList to quickly remove duplicates and convert the list to a set.
⚠️
Trying to cast an ArrayList directly to a HashSet without creating a new HashSet causes a ClassCastException.