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 :
- Take input in LinkedHashMap with keys and respective values.
- Create one array with data type the same as that of keys in LinkedHashMap.
- Create another array with data type the same as that of values in LinkedHashMap.
- Start LinkedHashMap traversal.
- Copy each key and value in two arrays.
- After completion of traversal, print both the arrays.
Below is the implementation of the above approach:
Java
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 ;
for (Map.Entry mapElement : lhm.entrySet()) {
Integer key = (Integer)mapElement.getKey();
int value = (( int )mapElement.getValue());
Keys[i] = key;
Values[i] = value;
i++;
}
System.out.print( "Array of Key -> " );
for (Integer key : Keys) {
System.out.print(key + ", " );
}
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)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!