遍历Map对象的方法

方法一:遍历条目entries  (键值都用到时)

  

Map<String, String> map = new HashMap<String, String>();
 
for (Map.Entry<String, String>entry : map.entrySet()) { 

  String key
= entry.getKey();

  String value
= entry.getValue();

}

 

方法二:单独遍历key或value  (只使用key或value时)

Map<String, String> map = new HashMap<String, String>();
 
//遍历map中的键
 
for (String key : map.keySet()) {
 
    System.out.println("Key = " + key);
 
}
 
//遍历map中的值
 
for (String value : map.values()) {
 
    System.out.println("Value = " + value);
 
}
 

 

方法三:使用Iterator遍历

Map<String, String> map = new HashMap<String, String>();
 
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
 
while (entries.hasNext()) {
 
    Map.Entry<String, String> entry = entries.next();
 
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
 
}
 

 

posted @ 2022-08-19 17:30  湘summer  阅读(312)  评论(0编辑  收藏  举报