In Java, a Set is a collection that contains only unique elements, while a List is a collection that allows duplicates and maintains the insertion order of its elements.
There are situations where it may be necessary to convert a Set to a List, for example, when you need to perform operations that are only supported by the List interface, such as accessing elements by their index.
This article will show you how to convert a Set to a List in Java.
Why conversion of Set to List in Java are required :
In Java, a Set is a collection that contains unique elements, meaning that it does not allow duplicates. On the other hand, a List is a collection that allows duplicates and maintains the order of elements.
There are several reasons why we might need to convert a Set to a List in Java:
- Ordered elements: If we need to maintain the order of elements, then we can convert a Set to a List. Since a List maintains the order of elements, converting a Set to a List will ensure that the elements are in the order they were added to the Set.
- Duplicates: If we need to allow duplicates, then we can convert a Set to a List. Since a List allows duplicates, converting a Set to a List will allow us to have multiple occurrences of the same element.
- API compatibility: Some APIs or methods may only accept a List as input, and in such cases, we need to convert a Set to a List to make use of the API.
- Convenience: In some cases, it may be more convenient to work with a List rather than a Set. For example, if we need to iterate over the elements of a collection multiple times, then it might be more efficient to convert a Set to a List and iterate over the List multiple times.
Methods For Converting Set to List in Java
There are different methods for converting a Set to a List in Java. Here are some of the commonly used methods:
- Using the ArrayList constructor: The ArrayList constructor can take a Collection as an argument, and it will create a new ArrayList containing the elements of the Collection. We can pass the Set to this constructor to convert it to a List.
- Using the addAll() method of ArrayList: The ArrayList class has an addAll() method that can add all the elements of a Collection to the ArrayList. We can create a new ArrayList and then call the addAll() method with the Set as the argument to convert it to a List.
- Using the Streams API: We can also use the Streams API introduced in Java 8 to convert a Set to a List. We can create a stream of the Set, convert it to a List using the collect() method, and store the result in a new List.
- Using the conventional for loop : To convert a Set to a List using a conventional for loop in Java, you can create an empty List and iterate over the Set, adding each element to the List using the add() method.If you need to preserve the order, use a LinkedHashSet instead of a HashSet.
- Using List.copyOf() method: List.copyOf() is a Java 10 method that creates an immutable List from a Set. The resulting List is unmodifiable and cannot be modified. To create the List, pass the Set to the List.copyOf() method.
We are now going to look at codes and description for further understanding:
Approach 1: Converting Set To List In Java Using the ArrayList constructor
The most straightforward way to convert a set to a list is by passing the set as an argument while creating the list. This calls the constructor and from there onwards the constructor takes care of the rest.
Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
// Create a HashSet of integers
Set<Integer> a = new HashSet<>();
a.add(1);
a.add(2);
a.add(3);
a.add(1); // Duplicate value, HashSet will only add it once
// Create an ArrayList of integers from the HashSet
List<Integer> arr = new ArrayList<>(a);
// Print the ArrayList to the console
System.out.println(arr);
// Access the second element of the ArrayList and print it to the console
System.out.println(arr.get(1));
}
}
Output:
[1, 2, 3]2
Explanation of code:
- This Java code creates a Set “a” with integer values, converts it to an ArrayList “arr” using the ArrayList constructor.
- Prints the ArrayList and the element at index 1 to the console.
- The ArrayList “arr” contains the elements of the Set “a” in the order in which they were added to the Set, and the output shows the ArrayList and the element at index 1.
Approach 2: Converting Set To List In Java Using the addAll() method of ArrayList:
Lists have a method called addAll() that adds multiple values to the list at once. You might recall this operation from its use in merging two lists. addAll() also works for adding the elements of a set to a list.
Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
// Create a HashSet of integers
Set<Integer> a = new HashSet<>();
a.add(1);
a.add(2);
a.add(3);
a.add(1); // Duplicate value, HashSet will only add it once
// Create an empty ArrayList of integers
List<Integer> arr = new ArrayList<>();
// Add all elements of the HashSet to the ArrayList
arr.addAll(a);
// Print the ArrayList to the console
System.out.println(arr);
// Access the second element of the ArrayList and print it to the console
System.out.println(arr.get(1));
}
}
Output:
[1, 2, 3]
2
Explanation of code:
- This Java code creates a HashSet “a” with integer values.
- The code then creates an empty ArrayList “arr” using the ArrayList constructor with no arguments.
- The elements of the Set “a” are added to the ArrayList “arr” using the addAll() method.
- The ArrayList “arr” contains the elements of the Set “a” in the order in which they were added to the Set.
- Finally, the code prints the ArrayList “arr” to the console and retrieves the element at index 1 of the ArrayList using the get() method and prints it to the console.
Approach 3: Converting Set To List In Java Using the Streams API:
To convert a Set into a List using the Stream API collect() method, you can create a stream of the elements in the Set, use the collect() method to collect them into a new List, and then terminate the stream. Here’s an example:
Stream.collect() is available from Java 8 onwards. ToList collector collects all Stream elements into a List instance.
To specify the type of list use toCollection(ArrayList::new)
Code:
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Create a HashSet of integers
Set<Integer> a = new HashSet<>();
a.add(1);
a.add(2);
a.add(3);
a.add(1); // Duplicate value, HashSet will only add it once
// Create an empty ArrayList of integers
List<Integer> arr;
// Convert the HashSet to an ArrayList using Java 8 Streams
arr = a.stream().collect(Collectors.toList());
// Print the ArrayList to the console
System.out.println(arr);
// Access the second element of the ArrayList and print it to the console
System.out.println(arr.get(1));
}
}
Output:
[1, 2, 3]
2
Explanation of code:
This Java code creates a HashSet “a” with integer values, and then converts it to an ArrayList “arr” using the stream() method and the collect() method from the Collectors class.
- The code uses the stream() method to create a stream of the elements in the Set “a”.
- The collect() method is then used with Collectors.toList() to collect the elements of the stream into a List.
- The resulting List “arr” contains the elements of the Set “a” in the order in which they were added to the Set.
- Finally, the code prints the ArrayList “arr” to the console and retrieves the element at index 1 of the ArrayList using the get() method and prints it to the console.
Approach 4: Converting Set To List In Java Using the conventional for loop
We can use the good old for loop to explicitly copy the elements from the set to the list.
Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
// Create a HashSet of integers
Set<Integer> a = new HashSet<>();
a.add(1);
a.add(2);
a.add(3);
a.add(1); // Duplicate value, HashSet will only add it once
// Create an ArrayList from the HashSet using ArrayList constructor
List<Integer> arr = new ArrayList<>(a);
// Loop through the HashSet and add each element to the ArrayList
for (int i : a) {
arr.add(i);
}
// Print the ArrayList to the console
System.out.println(arr);
// Access the second element of the ArrayList and print it to the console
System.out.println(arr.get(1));
}
}
Output:
[1, 2, 3, 1, 2, 3]2
Explanation of code:
- This Java code creates a HashSet “a” with integer values.
- The code then converts the HashSet “a” to an ArrayList “arr” using the ArrayList constructor.
- The ArrayList “arr” contains the elements of the Set “a” in the order in which they were added to the Set.
- The code then redundantly iterates through the Set “a” and adds each element to the ArrayList “arr” using the add() method.
- Finally, the code prints the ArrayList “arr” to the console and retrieves the element at index 1 of the ArrayList using the get() method and prints it to the console.
Approach 5: Converting Set To List In Java Using List.copyOf() method:
In Java, We can use the List.copyOf() method to create a new List that contains the same elements as a given Set. This method takes the Set as an argument and returns an unmodifiable List containing the same elements as the original Set.
The list can’t contain any null elements. In case the set contains ‘null’, the method returns a null pointer exception.
Code:
import java.util.*;
public class SetToListExample {
public static void main(String[] args) {
// Create a Set of strings
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("orange");
// Convert the Set to a List
List<String> list = List.copyOf(set);
// Print the Set and List to the console
System.out.println("Set: " + set);
System.out.println("List: " + list);
}
}
Output:
Set: [banana, orange, apple]
List: [banana, orange, apple]
Explanation of code:
- Import the ‘java.util’ package, which contains the ‘Set’ and ‘List’ interfaces and their implementations.
- Define a public class ‘SetToList’.
- Define a main method with the ‘String[] args’ parameter.
- Create a ‘Set’ of strings and add three fruit strings to it.
- Convert the ‘Set’ to a ‘List’ using the ‘List.copyOf()’ method.
- Print the contents of the ‘Set’ and the ‘List’ to the console using ‘System.out.println()’.
Note that the order of elements in the List may not be the same as the order in the Set, since Set does not maintain the order of elements.
Best Approach for converting Set to List in Java
The ArrayList constructor is an efficient method to convert a Set into a List in Java. Here are the reasons for this sentence:
- The ArrayList constructor takes a Collection as input, which includes Set.
- When a Set is passed to the ArrayList constructor, it initializes the ArrayList with the size of the Set.
- The elements of the Set are added to the ArrayList in the order they are returned by the Set’s iterator.
- This approach avoids the overhead of creating a stream or iterator, and ensures that the order of elements in the resulting List matches the order in the original Set.
- The resulting List is mutable, which means that elements can be added, removed, or modified.
Sample Problems For Converting Set to List In Java
Sample Problem 1:
Write a program where you have a List of elements, but it may contain duplicates. You want to remove the duplicates and create a new List containing only the unique elements. You can do this by first converting the List to a Set (which automatically removes duplicates), and then converting the Set back to a List:
Solution:
Steps to remove duplicates from a List of elements and create a new List containing only the unique elements using Set and List in Java:
- Create a List with some duplicate elements.
- Create a new HashSet using the List, which automatically removes the duplicates.
- Create a new ArrayList using the HashSet, which contains only the unique elements.
- Print the resulting ArrayList to the console.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
// Create a List with some duplicate elements
List<String> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add("apple");
listWithDuplicates.add("banana");
listWithDuplicates.add("orange");
listWithDuplicates.add("banana");
listWithDuplicates.add("apple");
// Create a new HashSet using the List, which automatically removes the duplicates
Set<String> setWithoutDuplicates = new HashSet<>(listWithDuplicates);
// Create a new ArrayList using the HashSet, which contains only the unique elements
List<String> listWithoutDuplicates = new ArrayList<>(setWithoutDuplicates);
// Print the resulting ArrayList to the console
System.out.println(listWithoutDuplicates);
}
}
Output:
[banana, orange, apple]
In summary, you can remove duplicates from a List of elements and create a new List containing only the unique elements by creating a new HashSet using the List, and then creating a new ArrayList using the HashSet.
Sample problem 2:
Write a program where you have a List of elements, but you want to sort them in ascending order. You can do this by first converting the List to a TreeSet (which automatically sorts the elements), and then converting the TreeSet back to an ArrayList.
Solution:
Here are the steps to sort a List of integers in ascending order using TreeSet and ArrayList in Java:
- Create an unsorted List of integers.
- Create a new TreeSet using the List, which automatically sorts the elements.
- Create a new ArrayList using the TreeSet, which contains the elements in ascending order.
- Print the resulting ArrayList to the console.
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class SortList {
public static void main(String[] args) {
// Create an unsorted List of integers
List<Integer> unsortedList = new ArrayList<>();
unsortedList.add(5);
unsortedList.add(3);
unsortedList.add(9);
unsortedList.add(1);
// Create a new TreeSet using the List, which automatically sorts the elements
Set<Integer> sortedSet = new TreeSet<>(unsortedList);
// Create a new ArrayList using the TreeSet, which contains the elements in ascending order
List<Integer> sortedList = new ArrayList<>(sortedSet);
// Print the resulting ArrayList to the console
System.out.println(sortedList);
}
}
Output:
[1, 3, 5, 9]
In summary, We can sort a List of integers in ascending order by creating a new TreeSet using the List, and then creating a new ArrayList using the TreeSet.
Conclusion
We saw some really interesting methods to convert a set into a list. It’s important to pay attention to the type of list that is created from each method. Like copyOf() method produces an immutable list and can’t handle null elements. Whereas, stream.collect() doesn’t guarantee anything. Constructor and addAll() are the most trustworthy among the batch.
In conclusion, there are several ways to convert a Set into a List in Java:
- Using the ArrayList constructor that takes a Set as an argument.
- Using a conventional for loop to iterate over the Set and add its elements to a new List.
- Using the List.addAll() method to add all the elements of the Set to a new List.
- Using the Stream API collect() method to collect the elements of the Set into a new List.
- Using the List.copyOf() method available in Java 10 and later versions to create an immutable List containing the same elements as the original Set.
It is important to note that the order of the elements in the resulting List may not necessarily be the same as the order of the elements in the original Set. Additionally, if the Set contains null values, special care needs to be taken when converting it to a List, as List does not allow null values by default.