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. The task is to iterate through a LinkedHashMap using an Iterator. We use the Iterator object to iterate through a LinkedHashMap.
Input: Key - 2 : Value - 6 Key - 3 : Value - 4 Key - 6 : Value - 5 Key - 4 : Value - 10 Key - 5 : Value - 6 Output: Key = Value 2 = 6 3 = 4 6 = 5 4 = 10 5 = 6
1. Create a LinkedHashMap and add key, value pairs.
2. we convert our LinkedHashMap to entrySet using,
Set s = lhm.entrySet();
3. we define iterator for our set.
4. Using while loop we iterate through our linkedHashMap.
key=Value 2=6 3=4 6=8 4=10 5=6
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.