What is the best way to iterate objects on a Hashmap?

Asked

Viewed 22,775 times

37

What is the best way to iterate objects into one HashMap in Java to gain access to the key and value of each entry?

  • 1

    You want to iterate each input (key+value), only values, or only keys?

  • 1

    @jpkrohling I want to iterate over each entry, to have access to the two properties.

  • 1

    So I guess the @Ecil solution seems to suit you best :-)

  • 1

    It was what I found more interesting. I will still leave the topic open for a while to stimulate the staff to participate hehehe.

5 answers

50

I like to wear the bow for because the code gets thinner:

for (Map.Entry<String,Integer> pair : myHashMap.entrySet()) {
    System.out.println(pair.getKey());
    System.out.println(pair.getValue());
}
  • 2

    Short and clear, as it should be ;)

  • 1

    There are many people who often write polluted code because they do not know the details and novelties of the language, as I have done several times myself.

  • 1

    And after all it seems that this is the most optimized way. Source 1 and source 2.

13

Using the method entrySet(), Example:

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(); // avoids a ConcurrentModificationException
    }
}

Source: https://stackoverflow.com/questions/1066589/java-iterate-through-hashmap

Edit.: According to the tip of (Vitor de Mario) will a brief explanation between the difference of entrySet() and of LinkedHashMap<K,V>.

The entrySet() does not guarantee the iteration order, already the LinkedHashMap<K,V> will iterate exactly in the order you are displaying in the array. Source: https://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-sortedmap-in-java

  • 4

    I also recommend using Linkedhashmap as an implementation if you want to iterate.

  • 1

    @Vitordemario can post an example for us?

  • 1

    @Deividicavarzan the War just edited, that’s exactly what he said

  • I edited the post @Deividicavarzan, thanks for the tip Vitor

  • 2

    To help with other questions about maps (and Collections): http://i.imgur.com/ox9SLL9.png

  • 6

    Your source’s answer is from 2009, and it’s no longer the best way to iterate. The reason is that this was probably a more Jvms-compatible solution without generic support, or because of a lack of for() iterator support. Nowadays it is much easier to use for(), iterating the element, rather than using the iterator explicitly and cast.

Show 1 more comment

9

Can use functional operations:

map.forEach((key, value) -> {
   System.out.println("key: " + key + ", value: " + value);
});

Functioning in the IDEONE.

  • Very good for simple operations, but for my case that an excerpt of the code could launch exception, I decided to use the answer of for just below whereas the outline with try catch would go bad and the father method was already with the flag throws Exception, then you have to keep that in mind

6

    Map<Integer,String> mapa=new HashMap<Integer, String>();
    mapa.put(1, "ze");
    mapa.put(2, "mane");
    Set<Integer> chaves = mapa.keySet();  
    for (Iterator<Integer> it = chaves.iterator(); it.hasNext();){  
        Integer chave = it.next();  
        if(chave != null){  
            System.out.println(chave + mapa.get(chave));  
        }
    }  
  • 8

    Creating a Set<Integer> and then giving a "map.get()" is asking for problems... Easier to directly iterate inputs, rather than copy keys and iterate Set<Integer>.

3

There is also the option to use the library Guava. Take a look at API and in the Wiki maps class.

It has several interesting methods, for example Difference to get the difference between 2 maps, Transform*, filter*, etc. Depending on what you want to do, using one of these methods to transform, filter, etc. can generate simpler and easier to read code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.