LinkedHashMap with Looping
We can iterate Linkedhashmap using enhanced for loop with keyset() method or by using enhanced for loop with EntrySet() method or by using iterator
Case 1 :
Enhanced for loop with keyset()
Example
- import java.util.*;
- public class LinkedHashMapEnhancedForLoopExample {
- public static void main(String args[]) {
- LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
- lhm.put(1, “One”);
- lhm.put(2, “Two”);
- lhm.put(3, “Three”);
- Set keys = lhm.keySet();
- for(Integer key: keys){
- System.out.println(“Value of “+key+” is: “+lhm.get(key));
- }
- }
- }
import java.util.*; public class LinkedHashMapEnhancedForLoopExample { public static void main(String args[]) { LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>(); lhm.put(1, “One”); lhm.put(2, “Two”); lhm.put(3, “Three”); Set keys = lhm.keySet(); for(Integer key: keys){ System.out.println(“Value of “+key+” is: “+lhm.get(key)); } } }
In this program, we have accessed all the keys of LinkedHashMap using keySet() method and then iterated all the keys using enhanced for loop and accessed value by passing key in each iteration in the loop.
Case 2 :
Enhanced for loop with entrySet()
Example
- import java.util.*;
- public class LinkedHashMapEnhancedForLoopEntrySetExample {
- public static void main(String args[]) {
- LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
- lhm.put(1, “One”);
- lhm.put(2, “Two”);
- lhm.put(3, “Three”);
- for (Map.Entry entry : lhm.entrySet()) {
- Integer key = entry.getKey();
- Object value = entry.getValue();
- System.out.println(“Value of “+key+” is: “+value);
- }
- }
- }
import java.util.*; public class LinkedHashMapEnhancedForLoopEntrySetExample { public static void main(String args[]) { LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>(); lhm.put(1, “One”); lhm.put(2, “Two”); lhm.put(3, “Three”); for (Map.Entry entry : lhm.entrySet()) { Integer key = entry.getKey(); Object value = entry.getValue(); System.out.println(“Value of “+key+” is: “+value); } } }
Case 3 :
Using iterator
Example
- import java.util.*;
- public class LinkedHashMapIteratorExample {
- public static void main(String args[]) {
- LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
- lhm.put(1, “One”);
- lhm.put(2, “Two”);
- lhm.put(3, “Three”);
- Iterator it = lhm.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry pair = (Map.Entry)it.next();
- System.out.println(pair.getKey() + ” = ” + pair.getValue());
- }
- }
- }
import java.util.*; public class LinkedHashMapIteratorExample { public static void main(String args[]) { LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>(); lhm.put(1, “One”); lhm.put(2, “Two”); lhm.put(3, “Three”); Iterator it = lhm.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); System.out.println(pair.getKey() + ” = ” + pair.getValue()); } } }