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
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
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<Integer, Integer> lhm
= new LinkedHashMap<>();
lhm.put( 2 , 6 );
lhm.put( 3 , 4 );
lhm.put( 6 , 8 );
lhm.put( 4 , 10 );
lhm.put( 5 , 6 );
Set s = lhm.entrySet();
Iterator it = s.iterator();
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).
Share your thoughts in the comments
Please Login to comment...