java循环遍历map
时间: 2023-09-06 21:08:03 浏览: 106
在Java中,有多种方法可以循环遍历Map。在你提供的引用中,以下是三种常用的方法:
方法一:使用for循环遍历key或者value
```java
Map<String, String> map = new HashMap<>();
map.put("第一个对象", "1");
map.put("第二个对象", "2");
// 遍历key
for(String mapKey : map.keySet()){
System.out.println(mapKey);
}
// 遍历value
for(String mapValue : map.values()){
System.out.println(mapValue);
}
```
方法二:使用Iterator遍历Map
```java
Map<String, String> map = new HashMap<>();
map.put("第一个对象", "1");
map.put("第二个对象", "2");
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()){
Object mapKey = iterator.next();
System.out.println("key:" + mapKey + ", value:" + map.get(mapKey));
}
```
方法三:使用entrySet()方法遍历Map
```java
Map<String, String> map = new HashMap<>();
map.put("第一个对象", "1");
map.put("第二个对象", "2");
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Map.Entry<String, String> entry = entries.next();
String mapKey = entry.getKey();
String mapValue = entry.getValue();
System.out.println(mapKey + ":" + mapValue);
}
```
这些方法适用于不同的场景,选择哪种方法取决于你需要遍历Map的具体要求。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [[java] Map循环遍历的5种方法实现](https://blog.csdn.net/u010321872/article/details/127364551)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文