Java Set to List
There are the following ways to convert Set to List in Java:
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.
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.
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.
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.
List is: Cambridge Bristol Wales London England Scotland