Java Set to List
In this section, we will discuss how to convert Set (HashSet or TreeSet) into List (ArrayList or LinkedList).
There are the following ways to convert Set to List in Java:
- Native Approach
- Using Constructor (ArrayList or LinkedList)
- Using ArrayList addAll() Method
- Using Stream in Java
Native Approach
The logic for the native approach is very simple. In this approach, we simply create a Set (HashSet or TreeSet) and iterate over the Set and add all the elements of the Set to the list with the help of a loop.
SetToListExample1.java
Output:
ArrayList is: Cannes Bordeaux Marseille Nice Clermont-Ferrand Chartres Limoges Chamonix Paris
Using Constructor (ArrayList or LinkedList Class)
The logic is the same as above. The only difference is that we have used the constructor of the ArrayList and LinkedList class and passed set elements to the constructor.
SetToListExample2.java
Output:
ArrayList is: Sharjah Dhaid Kalba Hatta Dubai Abu Dhabi LinkedList is: Sharjah Dhaid Kalba Hatta Dubai Abu Dhabi
Using ArrayList.addAll() Method
The ArrayList.addAll() method appends all the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. It overrides the addAll() method of the AbstractCollection class.
SetToListExample3.java
Output:
ArrayList is: Texas Illinois Columbus California Austin Dallas San Jose LinkedList is: Texas Illinois Columbus California Austin Dallas San Jose
Using Stream in Java
If we use Stream to convert Set to List, first, we will convert Set to stream and then convert the stream to list. It works only in Java 8 or later versions.
stream(): The method stream() returns a regular object stream of a set or list.
Stream.collect(): The collect() method of the Stream class is used to accumulate elements of any Stream into a Collection.
Collectors.toList(): The method returns a Collector that collects the input elements into a new List.
Let’s see an example.
SetToListExample4.java
Output:
List is: Cambridge Bristol Wales London England Scotland