Java How to Convert Set to List with Example
Set to a List in Java by creating a new ArrayList and passing the set to its constructor like this: List<Type> list = new ArrayList<>(set);.Examples
How to Think About It
Algorithm
Code
import java.util.*; public class SetToList { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("cherry"); List<String> list = new ArrayList<>(set); System.out.println(list); } }
Dry Run
Let's trace converting a set {"apple", "banana", "cherry"} to a list.
Create Set
Set contains: [apple, banana, cherry]
Convert to List
List created from set: [banana, cherry, apple]
Print List
Output: [banana, cherry, apple]
| Step | Set Contents | List Contents |
|---|---|---|
| 1 | [apple, banana, cherry] | [] |
| 2 | [apple, banana, cherry] | [banana, cherry, apple] |
| 3 | [apple, banana, cherry] | [banana, cherry, apple] |
Why This Works
Step 1: Set to List Conversion
The ArrayList constructor accepts any collection, so passing the set copies all its elements into a new list.
Step 2: Order in List
Since sets do not guarantee order, the list order depends on the set implementation, but all elements are included.
Step 3: Result Usage
The new list can be used like any list, supporting duplicates and indexed access.
Alternative Approaches
import java.util.*; public class SetToListAddAll { public static void main(String[] args) { Set<Integer> set = Set.of(1, 2, 3); List<Integer> list = new ArrayList<>(); list.addAll(set); System.out.println(list); } }
import java.util.*; import java.util.stream.*; public class SetToListStream { public static void main(String[] args) { Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c")); List<String> list = set.stream().collect(Collectors.toList()); System.out.println(list); } }
Complexity: O(n) time, O(n) space
Time Complexity
Copying all elements from the set to the list requires iterating over each element once, so it is O(n).
Space Complexity
A new list is created to hold all elements, so extra space proportional to the number of elements is needed, O(n).
Which Approach is Fastest?
Using the ArrayList constructor is the fastest and simplest. Using addAll() is similar but slightly longer. Streams add overhead and are best for complex processing.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ArrayList constructor | O(n) | O(n) | Simple and fast conversion |
| addAll() method | O(n) | O(n) | Clear step-by-step addition |
| Streams | O(n) | O(n) | When further processing is needed |
new ArrayList<>(set) for a quick and simple conversion from set to list.