map的四种遍历方式
Map<String, String> map = new HashMap<String, String>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
// 遍历方式1
Set<String> set = map.keySet(); // 获取所有key键
Collection<String> list = map.values(); // 获取所有value值
// 遍历set
for (String s : set) {
System.out.print(s);
}
System.out.println();
// 遍历collection
for (String l : list) {
System.out.print(l);
}
System.out.println();
// 遍历方式2
Set<String> set1 = map.keySet(); // 获取所有key键
// 遍历key值
for (String s : set1) {
System.out.print(s);
// 根据key值获取对应value值
String value = map.get(s);
System.out.print(value);
System.out.println();
}
// 遍历方式3(map遍历使用最多)
Set<Entry<String, String>> set2 = map.entrySet(); // 获取map的Entry
// 遍历集合
for (Entry<String, String> e : set2) {
String key = e.getKey(); // 获取每个元素中key值
String value = e.getValue(); // 获取每个元素中value值
System.out.print(key);
System.out.print(value);
System.out.println();
}
// 遍历方式4(使用迭代器)
Set<Entry<String, String>> set3 = map.entrySet();
Iterator<Entry<String, String>> ites = set3.iterator();
while (ites.hasNext()) {
Entry<String, String> e = ites.next();
System.out.print(e.getKey());
System.out.print(e.getValue());
System.out.println();
}