Thứ Năm, 27 tháng 1, 2011

4 Ways to Traverse a Map

Usually I don't need to traverse a java.util.Map, which is meant to be looked up, not iterated through. I traverse a java.util.Map primarily for debugging purposem, to dump its content. In case you do need to, here are 4 ways I've tried, just as examples:
import static java.net.HttpURLConnection.*;

private static void traverseMap() {
final String lineSeparator = System.getProperty("line.separator");
Map data = new HashMap();
data.put(HTTP_OK, "HTTP_OK");
data.put(HTTP_FORBIDDEN, "HTTP_FORBIDDEN");
data.put(HTTP_NOT_FOUND, "HTTP_NOT_FOUND");

System.out.println(lineSeparator + "Using JDK 5 foreach and entry set");
Set entries = data.entrySet();
for(Map.Entry entry : entries) {
    Object key = entry.getKey();
    Object value = entry.getValue();
    System.out.println(key + " = " + value);
}

System.out.println(lineSeparator + "Using Iterator and entry set");
for(Iterator it = entries.iterator(); it.hasNext();) {
    Map.Entry entry = it.next();
    Object key = entry.getKey();
    Object value = entry.getValue();
    System.out.println(key + " = " + value);
}

System.out.println(lineSeparator + "Using JDK 5 foreach and key set");
for(Object key : data.keySet()) {
    Object value = data.get(key);
    System.out.println(key + " = " + value);
}

System.out.println(lineSeparator + "Using traditional Iterator and key set");
for(Iterator it = data.keySet().iterator(); it.hasNext();) {
    Object key = it.next();
    Object value = data.get(key);
    System.out.println(key + " = " + value);
}
}
You may have noticed I'm using primitive int numbers (200, 403, 404) as the map key. Thanks to auto-boxing in JDK 5, I can use primitive s and their wrapper types interchangeably. Another useful feature in JDK 5 used here is using static import to import all HTTP status constants from java.net.HttpURLConnection.

Source: http://javahowto.blogspot.com/2006/06/4-ways-to-traverse-map.html

Không có nhận xét nào:

Đăng nhận xét