Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How to iterate through a HashMap in Java

Damian99Damian99 USAMember Posts: 116

What is the best way to iterate through a HashMap in Java?

Tagged:

Comments

  • DavidMDavidM USAMember Posts: 342
    edited January 2014
    public static void printMyMap(Map map) {
        Iterator itr = map.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry pairs = (Map.Entry)it.next();
            System.out.println(pairs.getKey() + " = " + pairs.getValue());
            itr.remove(); // avoids  ConcurrentModificationException
        }
    }
    
  • GouthamKumarGouthamKumar NelloreMember Posts: 17

    Iterating over any of the Map implementation(Hashmap, TreeMap etc) is not very straight forward compared to other collections There are different ways you can iterate over Map, to iterate using advanced for loop and using the Iterator object. We will use following three different ways to traverse.
    Using entrySet() and for loop
    Using keyset() and for loop
    Using Iterator interface
    For clear understanding and for examle programs please follow the link http://tutorialswithexamples.com/how-to-iterate-through-map-or-hashmap-in-java/
    http://java.meritcampus.com/t/182/Hashmap

Sign In or Register to comment.