hashmap stream
时间: 2023-07-07 08:19:55 浏览: 53
可以使用Java 8中的Stream API来遍历和操作HashMap。以下是一个示例代码:
```java
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
// 遍历HashMap
hashMap.entrySet().stream().forEach(entry -> {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
});
// 过滤HashMap
Map<String, Integer> filteredMap = hashMap.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// 对HashMap进行操作
Map<String, Integer> modifiedMap = hashMap.entrySet().stream()
.map(entry -> new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue() * 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
```
以上代码演示了如何使用Stream API来遍历、过滤和操作HashMap。在遍历时,我们使用`entrySet()`方法获取HashMap中的键值对,然后使用`stream()`方法将其转换为Stream流。在过滤和操作时,我们可以使用`filter()`、`map()`等方法来对Stream进行处理,最后使用`collect()`方法将结果转换为Map类型的数据。