Java How to Convert ArrayList to HashSet Easily
HashSet set = new HashSet<>(arrayList); .Examples
How to Think About It
Algorithm
Code
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); } }
Dry Run
Let's trace converting ["apple", "banana", "apple"] from ArrayList to HashSet.
Start with ArrayList
ArrayList contains ["apple", "banana", "apple"]
Create HashSet from ArrayList
HashSet now contains unique elements from ArrayList: ["apple", "banana"]
Print HashSet
Output is [banana, apple] (order may vary)
| Step | ArrayList | HashSet |
|---|---|---|
| 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
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); } }
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); } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| HashSet constructor | O(n) | O(n) | Simple and fast conversion |
| addAll() method | O(n) | O(n) | When you want to add conditionally or incrementally |
| Streams | O(n) | O(n) | When processing/filtering before conversion |