java 遍历 map集合\
时间: 2023-09-09 17:14:11 浏览: 97
java-遍历map
3星 · 编辑精心推荐
Java中遍历Map集合有多种方式,以下是其中的几种常用方法:
1. 使用for-each循环遍历Map集合
```java
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
```
2. 使用Iterator迭代器遍历Map集合
```java
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
```
3. 遍历Map的键或值
```java
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
// 遍历键
for (String key : map.keySet()) {
System.out.println("key = " + key);
}
// 遍历值
for (String value : map.values()) {
System.out.println("value = " + value);
}
```
以上是常见的几种遍历Map集合的方式,根据需求选择合适的方法即可。
阅读全文