Open In App

How to Convert LinkedHashMap to List in Java?

Improve
Improve
Like Article
Like
Save
Share
Report

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);
    }
}


Output

Key -> [2, 4, 5, 6, 3]
Value -> [5, 6, 16, 63, 18]

Time Complexity : O(n)



Last Updated : 17 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads