iterate through map hashmap linkedhashmap in java

How to iterate through Map.. MashMap, LinkedHashMap ...  in Java
Method 1 : If you're only interested in the keys, you can iterate through the keySet() of the map:
Map map = ...;
for (String key : map.keySet()) {
    // ...
}

Method 2 :
If you only need the values, use values():
for (Object value : map.values()) {
    // ...
}

Method 3  : If you want both the key and value, use entrySet():

for (Map.Entry entry : map.entrySet()) { 
 String key = entry.getKey(); 
 Object value = entry.getValue(); 
 // ...
}


Method 4 :using Iterator 
public static void printMap(Map mp) { 
 Iterator it = mp.entrySet().iterator(); 
  while (it.hasNext()) { 
    Map.Entry pairs = (Map.Entry)it.next(); 
    System.out.println(pairs.getKey() + " = " + pairs.getValue()); 
    it.remove(); 
  } 
}
Source : java-iterate-through-hashmap

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...