- Convert Set to List in Java and Vice-versa
- How to Convert Set to List in Java
- Initializing a set
- Converting Set to List in Java
- 1. List Constructor with Set argument
- 2. Using conventional for loop
- 3. List addAll() method
- 4. Stream API collect() method
- 5. List.copyOf() method
- Conclusion
- How to convert a set to a list in Java
- Conversion
- Implementation of the first method
- Implementation of the second method
- Java set to list string
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Convert Set to List in Java and Vice-versa
In Java, List and Set are Collections types to store elements. List is an index-based ordered collection, and Set is an unordered collection. List allows duplicate elements, but Set contains only unique elements. Both collection types are quite different and have their own usecases.
In this Java tutorial, Learn to convert a specified Set to a List. Also, learn to reverse convert List to Set, a useful method to remove duplicate elements from a list.
We will be using the following Set to List type in different ways.
1.1. Using List Constructor
To convert a given Set to a List, we can use the ArrayList constructor and pass HashSet as the constructor argument. It will copy all elements from HashSet to the newly created ArrayList.
ArrayList arrayList = new ArrayList(set); Assertions.assertEquals(3, arrayList.size());
Another useful method to get a List with Set elements is to create an empty list instance and use its addAll() method to add all the elements of the Set to List.
ArrayList arrayList = new ArrayList<>(); arrayList.addAll(set); Assertions.assertEquals(3, arrayList.size());
First, convert the Set to Stream, and then collect the Stream elements to List.
List list = set.stream().toList(); Assertions.assertEquals(3, list.size());
We might need to create a HashSet from a specified ArrayList when we want to remove duplicates from the list because sets do not allow duplicate items.
Let us begin with creating a List instance, and then we will convert it to the Set. The list contains 7 items, but only 4 unique items. So the Set size must be 4 in each method.
List list = List.of(1, 2, 3, 3, 3, 5, 5);
Similar to the previous example, we can use the constructor HashSet(collection) to convert to initialize a HashSet with the items from the ArrayList.
Set set = new HashSet(list); Assertions.assertEquals(4, set.size());
The Set.addAll(list) adds all of the elements in the specified collection to this set if they’re not already present.
Set set = new HashSet(); set.addAll(list); Assertions.assertEquals(4, set.size());
Similar to the previous section, we can convert a set to list using the Stream as follows:
Set set = list.stream().collect(Collectors.toSet()); Assertions.assertEquals(4, set.size());
How to Convert Set to List in Java
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Lists in Java are ordered collection of data, whereas sets are an unordered collection of data. A list can have duplicate entries, a set can not. Both the data structures are useful in different scenarios. Knowing how to convert a set into a list is useful. It can convert unordered data into ordered data.
Initializing a set
import java.util.*; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); System.out.println(a); > >
The add() method of HashSet adds the elements to the set. Note that the elements are distinct. There is no way to get the elements according to their insertion order as the sets are unordered.
Converting Set to List in Java
Let’s convert the set into a list. There are multiple ways of doing so. Each way is different from the other and these differences are subtle.
1. List Constructor with Set argument
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.
import java.util.*; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr = new ArrayList>(a); System.out.println(arr); System.out.println(arr.get(1)); > >
Since the set has been converted to a list, the elements are now ordered. That means we can use the get() method to access elements by index.
2. Using conventional for loop
We can use the good old for loop to explicitly copy the elements from the set to the list.
import java.util.*; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr = new ArrayList>(a); for (int i : a) arr.add(i); System.out.println(arr); System.out.println(arr.get(1)); > >
For loop goes over the set element by element and adds the elements to the list.
3. List addAll() method
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.
import java.util.*; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr = new ArrayList>(); arr.addAll(a); System.out.println(arr); System.out.println(arr.get(1)); > >
4. Stream API collect() method
Stream.collect() is available from Java 8 onwards. ToList collector collects all Stream elements into a List instance.
import java.util.*; import java.util.stream.Collectors; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr; arr = a.stream().collect(Collectors.toList()); System.out.println(arr); System.out.println(arr.get(1)); > >
The documentation for stream.collect() mentions that there is no guarantee on the type, mutability, serializability, or thread-safety of the List returned. If more control over the returned List is required, use toCollection(Supplier). To specify the type of list use toCollection(ArrayList::new)
import java.util.*; import java.util.stream.Collectors; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr; arr = a.stream().collect(Collectors.toCollection(ArrayList::new)); System.out.println(arr); System.out.println(arr.get(1)); > >
5. List.copyOf() method
Java 10 onwards List has a copyOf() method. The method returns an unmodifiable List containing the elements of the given Collection, in its iteration order. The list can’t contain any null elements. In case the set contains ‘null’, the method returns a null pointer exception.
import java.util.*; import java.util.stream.Collectors; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); ListInteger> arr; arr = List.copyOf(a); System.out.println(arr); System.out.println(arr.get(1)); > >
Adding a null in the set and trying to convert to a list :
import java.util.*; import java.util.stream.Collectors; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); a.add(null); ListInteger> arr; arr = List.copyOf(a); System.out.println(arr); System.out.println(arr.get(1)); > >
If you try to add an element to an immutable list you’ll get an error that looks like the following. Using the addAll() method to convert set with null element to a list :
import java.util.*; import java.util.stream.Collectors; public class Main public static void main(String[] args) SetInteger> a = new HashSet>(); a.add(1); a.add(2); a.add(3); a.add(1); a.add(null); ListInteger> arr = new ArrayList>(); arr.addAll(a); // arr = List.copyOf(a); System.out.println(arr); System.out.println(arr.get(1)); > >
Note that the null appears at the beginning of the list.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
How to convert a set to a list in Java
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
A Java set is a part of the java.util package; it extends the java.util.Collection interface. A Java set does not allow any duplicate item and allows only one null element.
A Java list is an ordered collection of items. Unlike a Java Set, a Java list can accommodate duplicate values.
Conversion
There are two methods used to convert a set to a list:
- Adding all the elements of the set to the list individually.
- Using the constructor of the list and passing the set to it.
Implementation of the first method
import java.util.*;import java.util.stream.*;class example// Generic function to convert set to listpublic static List convertSetToList(Set set)// create an empty listList list = new ArrayList<>();// push each element in the set into the listfor (T t : set)list.add(t);// return the listreturn list;>public static void main(String args[])// Create a Set using HashSetSet hash_Set = new HashSet();// Add elements to sethash_Set.add("Educative's");hash_Set.add("example");hash_Set.add("Set");hash_Set.add("to");hash_Set.add("list");// Print the SetSystem.out.println("Set: " + hash_Set);// construct a new List from SetList list = convertSetToList(hash_Set);// Print the ListSystem.out.println("List: " + list);>>Implementation of the second method
import java.util.*;import java.util.stream.*;class example// Generic function to convert set to listpublic static List convertSetToList(Set set)// create a list from SetList list = new ArrayList<>(set);// return the listreturn list;>public static void main(String args[])// Create a Set using HashSetSet hash_Set = new HashSet();// Add elements to sethash_Set.add("Educative's");hash_Set.add("example");hash_Set.add("Set");hash_Set.add("to");hash_Set.add("list");// Print the SetSystem.out.println("Set: " + hash_Set);// construct a new List from SetList list = convertSetToList(hash_Set);// Print the ListSystem.out.println("List: " + list);>>Learn in-demand tech skills in half the time
Java set to list string
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 weekLike/Subscribe us for latest updates or newsletter