今天一朋友问我有关Map集合的遍历问题,说真的当时真是懵了似懂非懂的,下面我通过查阅资料,具体内容整理如下:
public static void main(String[] args){
Map map=new HashMap();
map.put("1","张三");
map.put("2","李四");
map.put("3","王五");
}
第一种方法:通过Map.keySet遍历key和value
for(String key:map.keySet()){
System.out.print("key="+key);
System.out.println("value="+map.get(key));
}
第二种方法:通过Map.entrySet和迭代器遍历Map
Iterator> car =map.entrySet().interator(); while(car.hasNext()){ Map.Entry entry=car.next(); System.out.println("key="+entry.getKey()+"and value="+entry.getValue()); }
第三种方法:Map.entrySet()加for in 循环(推荐):
for(Map.Entryentry:map.entrySet()){ System.out.println("key="+entry.getKey()+"and value="+entry.getValue()); }
注:Map.entrySet()返回的是一个Set
第四种方法:通过Map.values():
for(String val:map.Values()){
System.out.println("value="+v);
}
以上四种方法介绍了Map集合的遍历代码,希望能够帮助到大家。



