ITERATE THROUGH A HASHMAP

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
Java 
 999  View(s)
Ratings:
Rate this:
What's the best way to iterate over the items in a HashMap?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Iterate through a HashMap

    Iterate through the entrySet like so:

    public static void printMap(Map mp) {
        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }
    }

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

    Map<String, Object> map = ...;
    for (String key : map.keySet()) {
        // ...
    }
    If you only need the values, use values():

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!