不同方式遍历Map集合(全)
今天一朋友问我有关Map集合的遍历问题,说真的当时真是懵了似懂非懂的,下面我通过查阅资料,具体内容整理如下:
publicstaticvoidmain(String[]args){
Map<String,String>map=newHashMap<String,String>();
map.put("1","张三");
map.put("2","李四");
map.put("3","王五");
}
第一种方法:通过Map.keySet遍历key和value
for(Stringkey:map.keySet()){
System.out.print("key="+key);
System.out.println("value="+map.get(key));
}
第二种方法:通过Map.entrySet和迭代器遍历Map
Iterator<Map.Entry<String,String>>car=map.entrySet().interator();
while(car.hasNext()){
Map.Entry<String,String>entry=car.next();
System.out.println("key="+entry.getKey()+"andvalue="+entry.getValue());
}
第三种方法:Map.entrySet()加forin循环(推荐):
for(Map.Entry<String,String>entry:map.entrySet()){
System.out.println("key="+entry.getKey()+"andvalue="+entry.getValue());
}
注:Map.entrySet()返回的是一个Set<Map<k,v>>,Map.Entry是一个接口,表示一个键值对(映射项),而Set<Map<k,v>>则表示映射项的Set。
第四种方法:通过Map.values():
for(Stringval:map.Values()){
System.out.println("value="+v);
}
以上四种方法介绍了Map集合的遍历代码,希望能够帮助到大家。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下