Map Iteration in Java
Programming Posted by Petter Hesselberg Sun, October 28, 2007 12:59Here's one common idiom for iterating over the values in a map:
private Map<String, String> strings = new ArrayList<String>();
public Iterable<String> strings() {
_ _ List<String> ret = new ArrayList<String>();
_ _ for (String key : strings.keySet()) {
_ _ _ _ String value = strings.get(key);
_ _ _ _ ret.add(value);
_ _ }
_ _ return ret;
}
Although this works correctly, it's woefully inefficient. Use keySet() if you only want the keys; use values() if you only want the values:
public Iterable<String> strings() {
_ _ List<String> ret = new ArrayList<String>();
_ _ for (String value : strings.values()) {
_ _ _ _ ret.add(value);
_ _ }
_ _ return ret;
}
When you want both key and value, use entrySet instead:
public Iterable<String> strings() {
_ _ List<String> ret = new ArrayList<String>();
_ _ for (Entry<String, String> entry : strings.entrySet()) {
_ _ _ _ System.out.println("Adding value for key " + entry.getKey());
_ _ _ _ ret.add(entry.getValue());
_ _ }
_ _ return ret;
}
My apologies for the underlines; indentation's a bit of a challenge in these here parts of the web.
Comments(0)