Iterating over a dictionary in Java
Forums:
Map<Integer, String> dic = new HashMap<Integer, String>() {{
put(1, "one");
put(2, "two");
}};
String str = "";
for (Entry<Integer, String> entry : dic.entrySet()) {
str += (str == "" ? "{" : ", ") +
String.format("%d=%s", entry.getKey(), entry.getValue());
}
str += "}";
//str is "{1=one, 2=two}"
str = "";
for (String value : dic.values()) {
str += (str == "" ? "" : ", ") + value;
}
//str is "one, two"
- Log in to post comments