How to iterate LinkedHashMap in Java?
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.
There are basically two ways to iterate over LinkedHashMap:
- Using keySet() and get() Method
- Using entrySet() and Iterator
Method 1: Iterating LinkedHashMap using keySet() and get() Method
Syntax:
linked_hash_map.keySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having the keys of the LinkedHashMap.
- Through keySet() method we will obtain a set having keys of the map.
- And then after running a loop over this set, we can obtain each key and its value using get() method.
Java
import java.util.LinkedHashMap;
import java.util.Set;
public class GFG {
public static void main(String a[])
{
LinkedHashMap<String, String> linkedHashMap
= new LinkedHashMap<String, String>();
linkedHashMap.put( "One" , "First element" );
linkedHashMap.put( "Two" , "Second element" );
linkedHashMap.put( "Three" , "Third element" );
Set<String> keys = linkedHashMap.keySet();
for (String key : keys) {
System.out.println(key + " -- "
+ linkedHashMap.get(key));
}
}
}
|
Output
One -- First element
Two -- Second element
Three -- Third element
Method 2: Iterating LinkedHashMap using entrySet() and Iterator
Syntax:
Linkedhash_map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the LinkedHashMap.
Java
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
public class GFG {
public static void main(String[] args)
{
LinkedHashMap<String, String> linkedHashMap
= new LinkedHashMap<String, String>();
linkedHashMap.put( "One" , "First element" );
linkedHashMap.put( "Two" , "Second element" );
linkedHashMap.put( "Three" , "Third element" );
Set entrySet = linkedHashMap.entrySet();
Iterator it = entrySet.iterator();
System.out.println( "LinkedHashMap entries : " );
while (it.hasNext())
System.out.println(it.next());
}
}
|
Output
LinkedHashMap entries :
One=First element
Two=Second element
Three=Third element
Last Updated :
25 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...