Java 8 中 Map 骚操作之 merge() 的使用方法
作者:唉我头发呢 发布时间:2022-03-31 01:19:27
Java 8 最大的特性无异于更多地面向函数,比如引入了lambda
等,可以更好地进行函数式编程。前段时间无意间发现了map.merge()
方法,感觉还是很好用的,此文简单做一些相关介绍。首先我们先看一个例子。
merge()
怎么用?
假设我们有这么一段业务逻辑,我有一个学生成绩对象的列表,对象包含学生姓名、科目、科目分数三个属性,要求求得每个学生的总成绩。加入列表如下:
private List<StudentScore> buildATestList() {
List<StudentScore> studentScoreList = new ArrayList<>();
StudentScore studentScore1 = new StudentScore() {{
setStuName("张三");
setSubject("语文");
setScore(70);
}};
StudentScore studentScore2 = new StudentScore() {{
setStuName("张三");
setSubject("数学");
setScore(80);
}};
StudentScore studentScore3 = new StudentScore() {{
setStuName("张三");
setSubject("英语");
setScore(65);
}};
StudentScore studentScore4 = new StudentScore() {{
setStuName("李四");
setSubject("语文");
setScore(68);
}};
StudentScore studentScore5 = new StudentScore() {{
setStuName("李四");
setSubject("数学");
setScore(70);
}};
StudentScore studentScore6 = new StudentScore() {{
setStuName("李四");
setSubject("英语");
setScore(90);
}};
StudentScore studentScore7 = new StudentScore() {{
setStuName("王五");
setSubject("语文");
setScore(80);
}};
StudentScore studentScore8 = new StudentScore() {{
setStuName("王五");
setSubject("数学");
setScore(85);
}};
StudentScore studentScore9 = new StudentScore() {{
setStuName("王五");
setSubject("英语");
setScore(70);
}};
studentScoreList.add(studentScore1);
studentScoreList.add(studentScore2);
studentScoreList.add(studentScore3);
studentScoreList.add(studentScore4);
studentScoreList.add(studentScore5);
studentScoreList.add(studentScore6);
studentScoreList.add(studentScore7);
studentScoreList.add(studentScore8);
studentScoreList.add(studentScore9);
return studentScoreList;
}
我们先看一下常规做法:
ObjectMapper objectMapper = new ObjectMapper();
List<StudentScore> studentScoreList = buildATestList();
Map<String, Integer> studentScoreMap = new HashMap<>();
studentScoreList.forEach(studentScore -> {
if (studentScoreMap.containsKey(studentScore.getStuName())) {
studentScoreMap.put(studentScore.getStuName(),
studentScoreMap.get(studentScore.getStuName()) + studentScore.getScore());
} else {
studentScoreMap.put(studentScore.getStuName(), studentScore.getScore());
}
});
System.out.println(objectMapper.writeValueAsString(studentScoreMap));
// 结果如下:
// {"李四":228,"张三":215,"王五":235}
然后再看一下merge()
是怎么做的:
Map<String, Integer> studentScoreMap2 = new HashMap<>();
studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
studentScore.getStuName(),
studentScore.getScore(),
Integer::sum));
System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
// 结果如下:
// {"李四":228,"张三":215,"王五":235}
merge()简介
merge()可以这么理解:它将新的值赋值到 key (如果不存在)或更新给定的key 值对应的 value,其源码如下:
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = this.get(key);
V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
if (newValue == null) {
this.remove(key);
} else {
this.put(key, newValue);
}
return newValue;
}
我们可以看到原理也是很简单的,该方法接收三个参数,一个 key 值,一个 value,一个remappingFunction,如果给定的key不存在,它就变成了put(key, value)。但是,如果 key 已经存在一些值,我们remappingFunction可以选择合并的方式,然后将合并得到的newValue赋值给原先的 key。
使用场景
这个使用场景相对来说还是比较多的,比如分组求和这类的操作,虽然 stream 中有相关groupingBy()方法,但如果你想在循环中做一些其他操作的时候,merge()还是一个挺不错的选择的。
其他
除了merge()方法之外,我还看到了一些Java 8 中map相关的其他方法,比如putIfAbsent、compute()、computeIfAbsent()、computeIfPresent,这些方法我们看名字应该就知道是什么意思了,故此处就不做过多介绍了,感兴趣的可以简单阅读一下源码(都还是挺易懂的),这里我们贴一下compute()(Map.class)的源码,其返回值是计算后得到的新值:
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = this.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
if (oldValue == null && !this.containsKey(key)) {
return null;
} else {
this.remove(key);
return null;
}
} else {
this.put(key, newValue);
return newValue;
}
}
来源:https://www.cnblogs.com/yxy1995/p/15029971.html


猜你喜欢
- 在有些产品的研发过程中,一般我们都有很多条数据记录在一个LOG文件中。在查看最新的数据记录都是从最开始保存的那条开始存储,所以,参考了网上一
- 日常开发中,判断邮箱是少不了的,这个我以**C#**为例,来写一个判断方法,正则表达式是通用的,CV就可以首先引入正则需要使用的命名空间//
- 操作步骤如下一、dropzone导入01.dropzone官网下载其插件压缩包并复制项目;02.将CSS和JS文件在HTML文件中引入;//
- 通过路径从磁盘直接读取图片这段时间在做Springboot和Vue的例子,读取图片给出路径直接可以读,太方便了,一直么有搞懂为什么。后面看到
- 最近一直在写c#的时候一直遇到这个报错,看的我心烦。。。准备记下来以备后续只需。参考博客:https://segmentfault.com/
- 通常我们在进行数据绑定的时候,常用的数据源有DataSet、DataTable、BindingList<T>、还有强类型数据源。
- mybatis的大于小于号转义符号言简意赅!如下XML转义字符<<小于号>>大于号<=
- 最近遇到了一个问题,一份很老的代码要修改里面的变量,源码早就和开发者一起不知去向,其中引用了一些jar包导致无法直接编译,只能直接修改.cl
- 一、注解的概念1、注解官方解释注解叫元数据,一种代码级别的说明,它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举在同一个层次,它可
- 《IDEA 破解新招 - 无限重置30天试用期》,这种方法适用idea2021以下所有版本,亲测idea2020.3成功激活,其他版本自测吧
- 前言开发系统时,有时候在实现功能时,删除操作需要实现逻辑删除就是将数据标记为删除,而并非真的物理删除(非DELETE操作),查询时需要携带状
- 1、JDK1.8之前:假设有实体类User,里面有字段id,我们将相同id的User进行分组,并存放在Map中。(例子不是很恰当,但很能说明
- 1.例如下面的代码片段,Toast类的第一个参数接受一个Context对象:@Override protected Dialog onCr
- 在 Java 中,方法调用一般通过 Virtual Call 还有 Classic Call。Classic Call 就是直接指向方法的地
- spring boot实现自动输出word文档功能本文用到Apache POI组件组件依赖在pom.xml文件中添加<dependen
- /** 获取昨天日期 方法一,这个方法好像有点慢*/Date dt = new Date(); Calendar cal = Calenda
- 使用enum进行定义/*枚举类型演示*/#include <stdio.h>int main() { enum /*
- 说在前面大一软件工程在读,java萌新一只,第一次写博客,技术很菜勿喷。如有错误欢迎指出!这个小程序是给朋友的生日礼物,耗时半天,实际写起来
- 监听通知Android 中的 AccessibilityService 可以监听通知信息的变化,首先需要创建一个无障碍服务,这个教程可以自行
- 一、前言拷贝这个词想必大家都很熟悉,在工作中经常需要拷贝一份文件作为副本。拷贝的好处也很明显,相较于新建来说,可以节省很大的工作量。在Jav