LinkedHashMap is predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, in LinkedHashMap insertion order is preserved.
We to convert LinkedHashMap to ArrayList. A Map store data in pair of Key and Value while converting a LinkedHashMAp to ArrayList we will store keys of Map in a separate List, similarly store value in another List, look example and algorithm for better understanding.
Example :
Input : { 1 = 3, 4 = 2, 6 = 5, 2 = 1 } output : Key -> [ 1, 4, 6, 2 ] value -> [ 3, 2, 5, 1] Input : { 2 = 10, 4 = 4, 6 = 23, 8 = 12 } output : Key -> [ 2, 4, 6, 6 ] value -> [ 10, 4, 23, 12]
Algorithm :
- Use For/while loop for iteration in LinkedHashMap
- Take two different ArrayList for Keys and their Respected Values.
- Now iterate through for-Each Loop in LinkedhashMap and add keys and values with their defined ArrayList
Pseudo code :
for (Map.Entry<Object, Object> it : l.entrySet()) { l1.add(it.getKey()); l2.add(it.getValue()); } Here, l is LinkedHashMap l1 is Arraylist for keys l2 is Arraylist for Values
Example:
Java
// Java program to convert LinkedHashMap // to List import java.util.*; import java.io.*; class GFG { public static void main(String[] args) { LinkedHashMap<Object, Object> l = new LinkedHashMap<>(); l.put( 2 , 5 ); l.put( 4 , 6 ); l.put( 5 , 16 ); l.put( 6 , 63 ); l.put( 3 , 18 ); // Taking two ArrayList ArrayList<Object> l1 = new ArrayList<>(); ArrayList<Object> l2 = new ArrayList<>(); for (Map.Entry<Object, Object> it : l.entrySet()) { l1.add(it.getKey()); l2.add(it.getValue()); } System.out.print( "Key -> " ); System.out.println(l1); System.out.print( "Value -> " ); System.out.println(l2); } } |
Key -> [2, 4, 5, 6, 3] Value -> [5, 6, 16, 63, 18]
Time Complexity : O(n)