How to loop a Map in Java
Published: June 25, 2010 , Updated: June 25, 2010 , Author: mkyong
Here’s few ways to loop or iterate a Map or HashMap in Java.
package com.mkyong.common; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class LoopAMap{ public static void main(String[] args) { //initial a Map Map<String,String> map = new HashMap<String,String>(); map.put("1", "Jan"); map.put("2", "Feb"); map.put("3", "Mar"); map.put("4", "Apr"); map.put("5", "May"); map.put("6", "Jun"); //Map -> Set -> Iterator -> Map.Entry -> troublesome Iterator iterator=map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry mapEntry=(Map.Entry)iterator.next(); System.out.println("The key is: "+mapEntry.getKey() + ",value is :"+mapEntry.getValue()); } //more elegant way for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } //weired way, but work anyway for (Object key: map.keySet()) { System.out.println("Key : " + key.toString() + " Value : " + map.get(key)); } } }
Which ways to go? It’s your personal preference.
[...] over Map Interface these 2 links were very useful for me: Official Java Tutorial website and Mkyong’s website. Like this:LikeBe the first to like this [...]
Although I used to use the while edition in my first projects I agree that the for-each edition is indeed more elegant and efficient
fuck,I’t so simple………….
Your ‘weired way’ is a bad idea, since you’ll be doing a lot of unnecessary hashtable lookups by using map.get while iterating.
See: http://findbugs.sourceforge.net/bugDescriptions.html#WMI_WRONG_MAP_ITERATOR
Why is it so bad ? Evaluating hash code is supposed to be cheap.
Also makes more sense when you are grouping Objects for instance Map<String,List>).
It is cheap, but not free. I gives you extra complexity to your code. You will feel it every time, when you will have to process 100 messages per second.
That is not too much in fact. Try to process your emails for some strange service. I have 5k mails. Lets assume first ‘for’ (from this blog entry) gives extra 0,1 second. Now do it for all your users (assume 10k). It is 1k seconds extra ~16 minutes. It is all about scale!
Using entrySet() is slightly safer, esp for debugging, as it will is give you matching key/values even if a) hashCode/equals are broken, or more likely b) the map is modified while you are using it.
one more
for (Iterator it = fromPackage.iterator(); it.hasNext();) {
Descriptor resourse = it.next();
………
}