![]() |
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. Converting LinkedHashSet to Other CollectionsIn certain scenarios, we might need to convert the LinkedHashSet to any other collections like List or Map based on the requirement. This is a common requirement while dealing with diverse data structures or when we need to interface with APIs or libraries that expect different types of collections. List Conversion1. 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
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 IteratorBelow is the implementation of the above Program: Java
OutputExplaination 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 Map Conversion1. Using Constant Values :Java
Output :Explaination of the above Program:In the above program a LinkedHashset is created with some values and a HashMap is created, And forEach method is used to iterate over the LinkedHashSet and each element with a constant value (1) to the HashMap. 2. Using Derived ValuesJava
Output :Explaination of the above Program:In the above program a LinkedHashset is created with some values and a HashMap is created, And forEach method is used to iterate over the LinkedHashSet and each element with with a value derived from its length to HashMap. |
Reffered: https://www.geeksforgeeks.org
Java Programs |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |