Jun 8, 2012

Iterate over a Map using Java 5 generics

Iterate over a Map using Java 5 generics

One of the coolest features in Java 5 is the enhanced for loop. Instead of having to use clunky Iterators to loop through a Map, you can use the enhanced for loop just as though you were iterating over an array, a List, or other collection.

Another neat feature in Java 5 is the addition of generics, which help to promote type safety. If you try to stuff an object of the wrong type into your collection, you’ll get an error at compile time instead of runtime, which is usually a good thing. Our examples will use generics along with the enhanced for loop.

Old School example (using Iterator)

Map items = new HashMap();
//...
//fill the map with String, Object values
//...
Iterator it = items.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
String value = (Object) items.get(key);
//do stuff here
}

Java 5 example (using generics)

Map items = new HashMap();
//fill map with String, String values

for (Map.Entry
entry : items.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
//do stuff here
}


Using the enhanced for loop with generics really makes the code cleaner, and we don’t have to mess with type casting when retrieving the object from the collection. Just remember that the enhanced for loop does have limitations – for instance, we can’t use it if we want to remove an object from our collection. In that case, we would have to use an Iterator. But if you’re only retrieving the elements, the enhanced for loop is more than adequate.

No comments:

Post a Comment

Main Differences Between SVN and Git