List Conversion
1. Using Constructor: By utilizing the constructor of the desired List implementation (like ArrayList) and passing the LinkedHashSet as an argument.
List<String> list = new ArrayList<>(linkedHashSet);
Example of the above Program:
Java
// Java Program to Convert LinkedHashSet to List import java.util.*; // Driver Class public class LinkedHashSetToList { // Main function public static void main(String[] args) { // Create a LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add( "Apple" ); linkedHashSet.add( "Banana" ); linkedHashSet.add( "Orange" ); // Convert LinkedHashSet to List using constructor List<String> list = new ArrayList<>(linkedHashSet); // Print the LinkedHashSet and List System.out.println( "LinkedHashSet: " + linkedHashSet); System.out.println( "List: " + list); } } |
Output:
Explaination of the above Program:
In the above program A LinkedHashSet is created with some elements And then the ArrayList Constructor is used to convert the LinkedHashSet to List. And here is the output for the above program
2. Using Iterator
Below is the implementation of the above Program:
Java
// Java Program to Convert LinkedHashSet to List Using Iterator import java.util.*; // Driver Class public class LinkedHashSetToListUsingIterator { // Main Function public static void main(String[] args) { // Create a LinkedHashSet LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add( "Java" ); linkedHashSet.add( "python" ); linkedHashSet.add( "c#" ); // Convert LinkedHashSet to List using iterator List<String> list = new ArrayList<>(); Iterator<String> iterator = linkedHashSet.iterator(); while (iterator.hasNext()) { list.add(iterator.next()); } // Print the LinkedHashSet and List System.out.println( "LinkedHashSet: " + linkedHashSet); System.out.println( "List: " + list); } } |
Output
Explaination of the above Program:
In the above program A LinkedHashSet is created with some fields and an empty Arraylist is created , And then an ‘Iterator’ is used to iterate over the LinkedHashSet and each element to the ArrayList.And here is the output of the above Program
Converting LinkedHashSet to Different Collection Types in Java
In Java, LinkedHashSet is a Class in the Java Collections Framework that extends the Collection HashSet and maintains the insertion order of the elements. The underlined data structure of the LinkedHastSet is that the insertion order is preserved.