当前位置: 首页 > news >正文

高效使用Map的“新”方法

个人名片:
😊作者简介:一个为了让更多人看见许舒雅的宝贝的小白先生
🤡个人主页:🔗 许舒雅的宝贝
🐼座右铭:深夜两点半的夜灯依旧闪烁,凌晨四点的闹钟不止你一个。
🎅学习目标: 坚持前端的学习进度,做一个全栈开发工程师

Map的数据操作,你是不是还只会put、get方法?

Map是我们日常变成中十分常用的数据接口,在JDK8中,Map引入了几个新方法,可以简化我们在实际写代码过程中对Map的数据操作。

目录

🌟1.getOrDefault方法

🌟2. foreach

🌟3.merge

🌟4.putIfAbsent

🌟5.computer

🌟6.computeIfAbsent

🌟7.computeIfPresent


🌟1.getOrDefault方法

使用 getOrDefault 方法获取键为 "key1" 的值,如果不存在则返回默认值 "defaultValue"

public class MapTest {public static void main(String[] args) {// 测试 put() 方法testGetOrDefault();}private static void testGetOrDefault() {Map<String, String> map = new HashMap<>();map.put("key1", "value1");map.put("key2", "value2");// 使用 getOrDefault 方法获取键为 "key1" 的值,如果不存在则返回默认值 "defaultValue"String value = map.getOrDefault("key3", "defaultValue");System.out.println(value); // 输出: value1}
}

🌟2. foreach

使用 forEach 方法遍历 Map 中的键值对

    public static void main(String[] args) {// 测试 testGetOrDefault() 方法// testGetOrDefault();// 测试testForeach()方法testForeach();}private static void testForeach() {Map<String, String> map = new HashMap<>();map.put("key1", "value1");map.put("key2", "value2");// 使用 forEach 方法遍历 Map 中的键值对map.forEach((key, value) -> {System.out.println("Key: " + key + ", Value: " + value);});}
}

🌟3.merge

使用 merge 方法合并键为 "key1" 的值,如果键不存在则添加新的键值对

    public static void main(String[] args) {// 测试 testGetOrDefault() 方法// testGetOrDefault();// 测试testForeach()方法// testForeach();// 测试testMerge()方法testMerge();}private static void testMerge(){Map<String, String> map = new HashMap<>();map.put("key1", "value1");map.put("key2", "value2");// 使用 merge 方法合并键为 "key1" 的值,如果键不存在则添加新的键值对map.merge("key1", "newValue", (oldValue, newValue) -> oldValue + " " + newValue);System.out.println(map.get("key1")); // 输出: value1 newValue}
}

🌟4.putIfAbsent

putIfAbsent()方法的作用是,如果指定的键不存在于映射中,则将指定的键值对添加到映射中。

    public static void main(String[] args) {// 测试 testGetOrDefault() 方法// testGetOrDefault();// 测试testForeach()方法// testForeach();// 测试testMerge()方法// testMerge();// 测试testPutIfAbsent()方法testPutIfAbsent();}//putIfAbsent()方法的作用是,如果指定的键不存在于映射中,则将指定的键值对添加到映射中。private static void testPutIfAbsent() {Map<String, String> map = new HashMap<>();map.put("key1", "value1");map.put("key2", "value2");// 使用 putIfAbsent 方法添加键值对,如果键不存在则添加新的键值对map.putIfAbsent("key3", "value3");map.putIfAbsent("key2", "newValue");System.out.println(map.get("key3")); // 输出: value3System.out.println(map.get("key2")); // 输出: value2}
}

🌟5.computer

computer()方法的作用是计算指定键的哈希码,并返回计算结果。

computer方法需要传入2个参数:key、function。主要有3步操作

  • 获取到key对应的oldValue,可能为null

  • 经过function计算获取newValue

  • put(key, newValue)

  public static void main(String[] args) {// 测试 testGetOrDefault() 方法// testGetOrDefault();// 测试testForeach()方法// testForeach();// 测试testMerge()方法// testMerge();// 测试testPutIfAbsent()方法// testPutIfAbsent();// 测试testComputer()方法testComputer();}//computer()方法的作用是计算指定键的哈希码,并返回计算结果。private static void testComputer() {Map<String, Integer> map = new HashMap<>();List<String> keys = Arrays.asList("apple","orange","banana","orange");for (String itemString : keys) {map.compute(itemString, (k,v)->{if(v==null){v=1;}else{v += 1;}return v;});}for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println(entry.getKey() + " : " + entry.getValue());}}
}

🌟6.computeIfAbsent

compute方法衍生出来的方法,这个方法只在key不存在的时候,执行computer计算,如果说key对应的value存在,就直接返回这个value。

我们需要计算斐波那锲数列的时候,可以使用这个方法来简化代码

    public static void main(String[] args) {// 测试 testGetOrDefault() 方法// testGetOrDefault();// 测试testForeach()方法// testForeach();// 测试testMerge()方法// testMerge();// 测试testPutIfAbsent()方法// testPutIfAbsent();// 测试testComputer()方法// testComputer();// 测试testComputeIfAbsent()方法testComputeIfAbsent();}//computeIfAbsent()方法的作用是,如果指定的键不存在于映射中,则将指定的键值对添加到映射中。private static void testComputeIfAbsent() {Map<Integer,Integer> map = new HashMap<>();map.put(0, 1);map.put(1, 1);System.out.println(fab(5,map));}private static int fab(int n,Map<Integer,Integer> map){return map.computeIfAbsent(n, k->fab(n-1,map)+fab(n-2,map));//n-1和n-2是递归的条件,k是递归的参数,k->fab(n-1,map)+fab(n-2,map)是递归的公式,k是递归的参数,k->fab(n-1,map)+fab(n-2,map)是递归的公式。}
}

🌟7.computeIfPresent

computeIfPresent()方法的作用是,如果指定的键存在于映射中,则计算指定键的值,并将计算结果更新到映射中。

    public static void main(String[] args) {// 测试 testGetOrDefault() 方法// testGetOrDefault();// 测试testForeach()方法// testForeach();// 测试testMerge()方法// testMerge();// 测试testPutIfAbsent()方法// testPutIfAbsent();// 测试testComputer()方法// testComputer();// 测试testComputeIfAbsent()方法// testComputeIfAbsent();// 测试testComputeIfPresent()方法testComputeIfPresent();}//computeIfPresent()方法的作用是,如果指定的键存在于映射中,则计算指定键的值,并将计算结果更新到映射中。private static void testComputeIfPresent() {Map<String, Integer> map = new HashMap<>();map.put("apple", 1);map.put("orange", 2);map.put("banana", 3);// 使用 computeIfPresent 方法计算指定键的值,并将计算结果更新到映射中map.computeIfPresent("apple", (key, value) -> value * 2);map.computeIfPresent("orange", (key, value) -> value * 2);map.computeIfPresent("banana", (key, value) -> value * 2);// 输出更新后的映射for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println(entry.getKey() + " : " + entry.getValue());}}
}

 

这篇文章就到这里了,下次见!

🥇原创不易,还希望各位大佬支持一下!

👍点赞,你的认可是我创作的动力 !

🌟收藏,你的青睐是我努力的方向!

✏️评论,你的意见是我进步的财富!

http://www.xdnf.cn/news/766639.html

相关文章:

  • 用Python开启游戏开发之旅
  • 修改vscode切换上一个/下一个标签页快捷键
  • SpringBoot高校宿舍信息管理系统小程序
  • Java转义字符
  • PDF 转 HTML5 —— HTML5 填充图形不支持 Even-Odd 奇偶规则?(第一部分)
  • 自主设计一个DDS信号发生器
  • [ Qt ] | 与系统相关的操作(一):鼠标相关事件
  • Go整合Redis2.0发布订阅
  • 通过《哪吒》看人生百态
  • 数据结构与算法:图论——拓扑排序
  • GMDCMonitor企业版功能分享0602
  • Qt OpenGL 实现交互功能(如鼠标、键盘操作)
  • leetcode90.子集II:排序与同层去重的回溯优化策略
  • 【leetcode】459.重复的子字符串
  • MyBatis源码解析:从 Mapper 接口到 SQL 执行的完整链路
  • 正则表达式在Java中的应用(补充)
  • 初识CSS3
  • OIer常用的软件
  • 【001】利用github搭建静态网站_essay
  • 并发编程的源头
  • Flink CDC将MySQL数据同步到数据湖
  • C++ 标准输入输出 -- <iostream>
  • 【深度学习新浪潮】多模态模型如何处理任意分辨率输入?
  • LazyOwn RedTeam/APT 框架是第一个具有人工智能驱动的 CC 的 RedTeam 框架
  • 6.linux文本内容显示cat,more,less
  • 第七部分:第五节 - 数据关系与进阶查询 (TypeORM):仓库里复杂的配料组合
  • 第1篇:数据库中间件概述:架构演进、典型方案与应用场景
  • 微服务常用日志追踪方案:Sleuth + Zipkin + ELK
  • SCAU8642--快速排序
  • C++ 内存泄漏检测器设计