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.
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]
- 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:
Array of Key -> 2, 3, 5, 4, 6, Array of Values -> 6, 4, 7, 6, 8,
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.