当前位置: 首页 > 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.lqws.cn/news/81073.html

相关文章:

  • 模块二:C++核心能力进阶(5篇)篇二:《多线程编程:C++线程池与原子操作实战》(14万字深度指南)
  • openai-java
  • Java详解LeetCode 热题 100(23):LeetCode 206. 反转链表(Reverse Linked List)详解
  • 做好 4个基本动作,拦住性能优化改坏原功能的bug
  • ps色彩平衡调整
  • github 提交失败,连接不上
  • 数值与字典解决方案二十七讲:两列数据相互去掉重复值后合并
  • 【Java Web】速通Tomcat
  • 【性能调优系列】深入解析火焰图:从基础阅读到性能优化实战
  • 导入典籍数据
  • Docker 镜像原理
  • React 核心概念与生态系统
  • js的时间循环的讲解
  • sqlite-vec:谁说SQLite不是向量数据库?
  • 题目 3225: 蓝桥杯2024年第十五届省赛真题-回文字符串
  • 光伏功率预测 | LSTM多变量单步光伏功率预测(Matlab完整源码和数据)
  • 机器视觉图像处理之图像滤波
  • 从多巴胺的诱惑到内啡肽的力量 | 个体成长代际教育的成瘾困局与破局之道
  • Python----目标检测(《YOLO9000: Better, Faster, Stronger》和YOLO-V2的原理与网络结构)
  • 蓝云APP:云端存储,便捷管理
  • Linux入门(十三)动态监控系统监控网络状态
  • (Python网络爬虫);抓取B站404页面小漫画
  • 探秘 Minimax:AI 领域的创新先锋
  • C# 异常处理进阶:精准获取错误行号的通用方案
  • JS中的 WeakSet 和 WeakMap
  • Y1——链式前向星
  • 麒麟信安安装谷歌浏览器
  • JavaScript性能优化实战
  • 多群组部署
  • 3.需求分析与测试用例设计方法