Java中Map集合遍历常用方式
1、通过在for循环中使用entries实现Map的遍历
Map <String,String> hashMap = new HashMap<String,String>();
map.put("userName","userName");
map.put("password","password");
for(Map.Entry<String, String> entry : hashMap.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey+":"+mapValue);
}
2、通过在for循环中遍历key或者values
Map <String,String> hashMap = new HashMap<String,String>();
map.put("userName","userName");
map.put("password","password");
//获取key值
for(String key : hashMap.keySet()){
System.out.println(key);
}
//获取value值
for(String value : hashMap.values()){
System.out.println(value);
}
3、通过Iterator迭代器遍历
Iterator<Entry<String, String>> entries = hashMap.entrySet().iterator();
while(entries.hasNext()){
Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
4、通过键找值遍历
for(String key : hashMap.keySet()){
String value = hashMap.get(key);
System.out.println(key+":"+value);
}