map迭代无论是在面试中,还是在实际的开发中都会经常遇到。目前接触到的有四种方式,其中第一中和第四种原理差不多,废话不多说,上代码
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "张三");
map.put(2, "李四");
map.put(3, "王五");
map.put(4, "麻六");
map.put(4, "赵七");
System.out.println("map的大小:" + map.size());
System.out.println("方式一:通过Map.keySet遍历key和value:");
for (Integer key : map.keySet()) {
String s = map.get(key);
System.out.println(key + ": " + s);
}
System.out.println("方式二:通过Map.entrySet遍历key和value:");
System.out.println("推荐,尤其是容量大时");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("方式三:通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("方式四:通过Map.values()遍历所有的value,但不能遍历key");
for (String value : map.values()) {
System.out.println(value);
}
}
运行的结果如下:
总结:推荐使用第二种方式,效率高,在数据量比较大时效果比较明显,并且比较灵活的获取到map的key和value,便于代码的编写。