Open In App

How to Convert LinkedHashMap to Two Arrays in Java?

LinkedHashMap is a pre-defined class in java like HashMap. The only difference between LinkedHashMap and HashMap is LinkedHashMap preserve insertion order while HashMap does not preserve insertion order. LinkedHashMap can convert into two Arrays in java where one array is for key in LinkedHashMap and another array for Values. 

Example :



Input : LinkedHashMap = [2=6, 3=4, 5=7, 4=6]
Output:
Array of keys = [2, 3, 5, 4]
Array of Values = [6, 4, 7, 6]

Input : LinkedHashMap = [1=a, 2=b, 3=c, 4=d]
Output:
Array of keys = [1, 2, 3, 4]
Array of Values = [a, b, c, d]

Algorithm :

  1. Take input in LinkedHashMap with keys and respective values.
  2. Create one array with data type the same as that of keys in LinkedHashMap.
  3. Create another array with data type the same as that of values in LinkedHashMap.
  4. Start LinkedHashMap traversal.
  5. Copy each key and value in two arrays.
  6. After completion of traversal, print both the arrays.

Below is the implementation of the above approach:






// Java Program to Convert LinkedHashMap to Two Arrays
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        LinkedHashMap<Integer, Integer> lhm
            = new LinkedHashMap<>();
  
        lhm.put(2, 6);
        lhm.put(3, 4);
        lhm.put(5, 7);
        lhm.put(4, 6);
        lhm.put(6, 8);
  
        Integer[] Keys = new Integer[lhm.size()];
  
        Integer[] Values = new Integer[lhm.size()];
        int i = 0;
        
        // Using for-each loop
        for (Map.Entry mapElement : lhm.entrySet()) {
            Integer key = (Integer)mapElement.getKey();
  
            // Add some bonus marks
            // to all the students and print it
            int value = ((int)mapElement.getValue());
  
            Keys[i] = key;
            Values[i] = value;
            i++;
        }
        
        // printing all the element of array contain keys
        System.out.print("Array of Key -> ");
        for (Integer key : Keys) {
            System.out.print(key + ", ");
        }
  
        // iterate value array
        System.out.println();
        System.out.print("Array of Values -> ");
        for (Integer value : Values) {
            System.out.print(value + ", ");
        }
    }
}

Output
Array of Key -> 2, 3, 5, 4, 6, 
Array of Values -> 6, 4, 7, 6, 8, 

Time Complexity: O(n)


Article Tags :