首页 > 其他分享 >遍历Map对象的方法

遍历Map对象的方法

时间:2022-08-19 17:33:07浏览次数:70  
标签:Map 遍历 map 对象 value key entry

方法一:遍历条目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());
 
}
 

 

标签:Map,遍历,map,对象,value,key,entry
From: https://www.cnblogs.com/lxpblogs/p/16602105.html

相关文章