遍历map的几种方法

遍历map有几种方法,记录一下。

public class MapCollection {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1,"小花");
map.put(2,"小草");
map.put(3,"小红");
map.put(4,"小白");

System.out.println("-----通过Map.keySet()获取key,根据key调用map.get()获取值value------");
for (Integer key:map.keySet()) {
System.out.println(key+":"+map.get(key));
}

System.out.println("-----通过Map.entrySet()获取迭代器对象iterator,遍历key和value-----");
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}

System.out.println("-----通过Map.entrySet()遍历key和value-------");
for (Map.Entry<Integer,String> entry:map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}

System.out.println("-----通过Map.values()遍历所有的value-----");
System.out.println("-----此方法无法获key----------");
for (String value: map.values()) {
System.out.println(value);
}
}
}
原文地址:https://www.cnblogs.com/lifengSkt/p/13233482.html