Tuesday, August 4, 2009

Using Java's Foreach Loop on a Map

First introduced in Java 5, the foreach loop has been one of my favorite (and most used) improvements to the Java language. Here's how you can use the foreach loop over a Map:
Map myMap = new HashMap();

myMap.put("person1234","Troy Campano");

for(Map.Entry myMapEntry : myMap.entrySet()) {

System.out.println("key=" + myMapEntry.getKey());
System.out.println("value=" + myMapEntry.getValue());
}
It's that easy!

share on: facebook

0 comments: