Four methods of traversing Map object in Java

Mode 1 this is the most common and, in most cases, the most desirable traversal mode. Used when all key values are required.

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
for (Map.Entry<Integer, Integer> entry : map.entrySet()) { 
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}


Method 2 traverses the keys or values in the for each loop.

If you only need the key or value in the map, you can traverse through keySet or values instead of using entrySet.

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
//Traversing keys in a map 
for (Integer key : map.keySet()) { 
  System.out.println("Key = " + key); 
} 
//Traversing values in a map 
for (Integer value : map.values()) { 
  System.out.println("Value = " + value); 
}


Method 3 traverse with Iterator

Use generics:

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); 
while (entries.hasNext()) { 
  Map.Entry<Integer, Integer> entry = entries.next(); 
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}

Do not use generics:

Map map = new HashMap(); 
Iterator entries = map.entrySet().iterator(); 
while (entries.hasNext()) { 
  Map.Entry entry = (Map.Entry) entries.next(); 
  Integer key = (Integer)entry.getKey(); 
  Integer value = (Integer)entry.getValue(); 
  System.out.println("Key = " + key + ", Value = " + value); 
}

Method 4. Traversal by key finding (low efficiency)


Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
for (Integer key : map.keySet()) { 
  Integer value = map.get(key); 
  System.out.println("Key = " + key + ", Value = " + value);

Tags: Java

Posted on Sat, 30 Nov 2019 22:54:02 -0800 by bbbaldie