遍历Map的两种方式:
准备一个Map
Map<String, String> map = new HashMap<>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");
map.put("d", "dd");
map.put("e", "ee");
map.put("f", "ff");
- 使用entrySet进行遍历
Set<Map.Entry<String, String>> set = map.entrySet();
for (Map.Entry<String, String> entry : set) {
System.out.println(entry.getKey() + "__" + entry.getValue());
}
- 使用Iterator进行遍历
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey() + "__" + entry.getValue());
}
获取所有的key
Set<String> keySet = map.keySet();
for (String s : keySet) {
System.out.println(s);
}
获取所有的value
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
网友评论