Java8中的Stream和Lambda表达式提供了一种简单的、优雅的方式来操作集合,其中包括了Map。下面是一些在Map上使用Java 8新特性的示例:
- 遍历Map
使用 forEach
函数遍历Map:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
map.forEach((key, value) -> {
System.out.println(key + " = " + value);
});
- 过滤Map
使用 filter
函数过滤Map:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
Map<String, Integer> filteredMap = map.entrySet()
.stream()
.filter(entry -> entry.getKey().length() > 5)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(filteredMap);
- 转换Map
使用 map
函数转换Map:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
Map<String, String> convertedMap = map.entrySet()
.stream()
.map(entry -> new AbstractMap.SimpleEntry<>(entry.getKey(), String.valueOf(entry.getValue())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(convertedMap);
- 排序Map
使用 sorted
函数对Map进行排序:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 1);
map.put("orange", 2);
Map<String, Integer> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new));
System.out.println(sortedMap);
- 统计Map
使用 sum
函数统计Map中的元素:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
int sum = map.entrySet()
.stream()
.mapToInt(entry -> entry.getValue())
.sum();
System.out.println(sum);