方法一:使用在for循环中使用Entriey实现Map的遍历:
/**
* 最常见也是大多数情况下用的最多的,一般在键值对都需要使用
*/
Map<String,String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for(Map.Entry<String, String> entry : map.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey+":"+mapValue);
}
方法二:在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用
Map <String,String>map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for(String key : map.keySet()){
System.out.println(key);
}
for(String value : map.values()){
System.out.println(value);
}
方法三:通过forEach 方式
Map<String,String>map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.forEach((mapKey,mapValue)->{
System.out.println(mapKey+":"+mapValue);
});
方法四:通过Iterator遍历
Map<String,String>map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Map.Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}