Map的三种遍历方式
- 方式一:使用entries实现Map的遍历
- 方式二:在for循环中遍历key或者values,一般只适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好
- 方式三:通过Iterator遍历
方式一:使用entries实现Map的遍历
Map map=new HashMap();
map.put("周","杰伦");
map.put("方","文山");
for (Map.Entry entry:map.entrySet()){
String mapkey=entry.getKey();
String mapValue=entry.getValue();
System.out.println(mapkey+":"+mapValue);
}
方式二:在for循环中遍历key或者values,一般只适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好
Map map=new HashMap();
map.put("周","杰伦");
map.put("方","文山");
//key
for (String key:map.keySet()){
String value=map.get(key);
System.out.println(key+":"+value);
}
System.out.println("-----------------");
//value
for (String value:map.values()){
System.out.println(value);
}
方式三:通过Iterator遍历
Map map=new HashMap();
map.put("周","杰伦");
map.put("方","文山");
Iterator> entryIterator=map.entrySet().iterator();
while(entryIterator.hasNext()){
Map.Entry entry=entryIterator.next();
String key=entry.getKey();
String value=entry.getValue();
System.out.println(key+":"+value);
}