Java - Hash Map Iterating

Submitted by code_admin on Fri, 07/20/2018 - 12:59

If you're only interested in the keys, you can iterate through the keySet() of the map:

  1. Map<String, Object> map = ..;
  2. for (String key : map.keySet()) {
  3.     // ..
  4. }

If you only need the values, use values():

  1. for (Object value : map.values()) {
  2.     // ..
  3. }

Finally, if you want both the key and value, use entrySet():

  1. for (Map.Entry<String, Object> entry : map.entrySet()) {
  2.     String key = entry.getKey();
  3.     Object value = entry.getValue();
  4.     // ..
  5. }

Add Remove During iterating

Iterate through the entrySet like so:

  1. public static void printMap(Map mp) {
  2.     Iterator it = mp.entrySet().iterator();
  3.     while (it.hasNext()) {
  4.         Map.Entry pairs = (Map.Entry)it.next();
  5.         System.out.println(pairs.getKey() + " = " + pairs.getValue());
  6.         it.remove(); // avoids a ConcurrentModificationException
  7.     }
  8. }

Tags

RJM Article Type
Quick Reference