Open In App

Iterate through LinkedHashMap using an Iterator 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. The task is to iterate through a LinkedHashMap using an Iterator. We use the Iterator object to iterate through a LinkedHashMap.

Example



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 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).


Article Tags :