LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHashMap and print It.
Input : Key- 1 : Value-5 Key- 29 : Value-13 Key- 14 : Value-10 Key- 34 : Value-2 Key- 55 : Value-6 Output: 1, 29, 14, 34, 55
Method 1: Use for-each loop to iterate through LinkedHashMap. For each iteration, we print the respective key using getKey() method.
for(Map.Entry<Integer,Integer>ite : LHM.entrySet()) System.out.print(ite.getKey()+", ");
1, 29, 14, 34, 55,
Method 2: (Using keySet() method)
Parameters: The method does not take any parameters.
Return Value: The method returns a set having the keys of the hash map.
[One, Two, Three]
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.