Java8对Map的优雅操作

Java8中的Stream和Lambda表达式提供了一种简单的、优雅的方式来操作集合,其中包括了Map。下面是一些在Map上使用Java 8新特性的示例:

  1. 遍历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);
});
  1. 过滤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);
  1. 转换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);
  1. 排序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);
  1. 统计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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值