Map使用stream流
Map可以使用Java 8中引入的Stream流来进行操作。通过Stream流,我们可以对Map中的键值对进行过滤、映射、排序、聚合等操作。以下是一些常见的使用示例:
- 遍历Map: ``` Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3);
map.entrySet().stream() .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
2. 过滤Map:
Map<String, Integer> filteredMap = map.entrySet().stream() .filter(entry -> entry.getValue() > 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
3. 转换Map的值:
Map<String, String> convertedMap = map.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
4. 对Map进行排序:
Map<String, Integer> sortedMap = map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
5. 对Map的值进行聚合操作(求和):
int sum = map.values().stream() .reduce(0, Integer::sum);
```
这只是一些常规操作的示例,Stream流提供了丰富的操作方法,可以根据具体需求来灵活使用。
相关推荐
















