Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Iterate through LinkedHashMap using an Iterator in Java

  • Last Updated : 04 Jan, 2021

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.

Example

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.

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

Algorithm : 

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.    

Iterator it=s.iterator();

4. Using while loop we iterate through our linkedHashMap. 

while(it.hasNext())                      
     System.out.println(it.next()); 

Implementation

Java




// Java program to Iterate through LinkedHashMap using an
// Iterator
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // create a linkedhashmap
        LinkedHashMap<Integer, Integer> lhm
            = new LinkedHashMap<>();
  
        // add mappings
        lhm.put(2, 6);
        lhm.put(3, 4);
        lhm.put(6, 8);
        lhm.put(4, 10);
        lhm.put(5, 6);
  
        // create an entryset
        Set s = lhm.entrySet();
  
        // create an iterator
        Iterator it = s.iterator();
  
        // iterate an print the mappings
        System.out.println("key=Value");
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
Output
key=Value
2=6
3=4
6=8
4=10
5=6

Time Complexity: O(n).




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!