java遍历HashMap
时间: 2024-02-09 10:03:50 浏览: 92
基于HashMap遍历和使用方法(详解)
Java遍历HashMap有多种方法,以下是其中的几种:
1.使用Iterator遍历HashMap
```java
Map<String, Integer> map = new HashMap<>();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key:" + key + ", value:" + value);
}
```
2.使用For-Each循环遍历HashMap
```java
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key:" + key + ", value:" + value);
}
```
3.使用Lambda表达式遍历HashMap
```java
Map<String, Integer> map = new HashMap<>();
map.forEach((key, value) -> System.out.println("key:" + key + ", value:" + value));
```
4.使用Stream API遍历HashMap
```java
Map<String, Integer> map = new HashMap<>();
map.entrySet().stream().forEach(entry -> System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue()));
```
阅读全文