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.
1. Convert Set to List
We will be using the following Set to List type in different ways.
Set<Integer> set = Set.of(1, 2, 3);
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<Integer> arrayList = new ArrayList(set); Assertions.assertEquals(3, arrayList.size());
1.2. Using List.addAll()
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<Integer> arrayList = new ArrayList<>(); arrayList.addAll(set); Assertions.assertEquals(3, arrayList.size());
1.3. Using Stream
First, convert the Set to Stream, and then collect the Stream elements to List.
List<Integer> list = set.stream().toList(); Assertions.assertEquals(3, list.size());
2. Convert List to Set
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);
2.1. Using Set Constructor
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());
2.2. Using Set.addAll()
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());
2.3. Using Stream
Similar to the previous section, we can convert a set to list using the Stream as follows:
Set<Integer> set = list.stream().collect(Collectors.toSet()); Assertions.assertEquals(4, set.size());
Happy Learning !!
Read More: ArrayList Java Docs and HashSet Java Docs