1.Map.merge方法介绍

  jdk8对于许多常用的类都扩展了一些面向函数,lambda表达式,方法引用的功能,使得java面向函数编程更为方便。其中Map.merge方法就是其中一个,merge方法有三个参数,key:map中的键,value:使用者传入的值,remappingFunction:BiFunction函数接口(该接口接收两个值,执行自定义功能并返回最终值)。当map中不存在指定的key时,便将传入的value设置为key的值,当key存在值时,执行一个方法该方法接收key的旧值和传入的value,执行自定义的方法返回最终结果设置为key的值。

//map.merge方法源码
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}

 比如以下代码的含义:当name不存在时设置name的值为1,当name的值存在时,将值加1赋给name

public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("name", 1);
map.merge("name", 1, (oldValue, newValue) -> oldValue + newValue);
map.merge("count", 1, (oldValue, newValue) -> oldValue + newValue);
System.out.println(map);
}
//返回结果
//{count=1, name=2}

2.map.merge()方法使用场景

  merge方法在统计时用的场景比较多,这里举一个统计学生总成绩的例子来说明。现在有一个学生各科成绩的集合,要统计每个学生的总成绩,以下给出使用merge方法与不使用的写法

public class StudentScoreSum {

    @Data
static class StudentScore {
private Integer sid;
private String scoreName;
private Integer score; public StudentScore(Integer sid, String scoreName, Integer score) {
this.sid = sid;
this.scoreName = scoreName;
this.score = score;
} public StudentScore() {
}
} public static void main(String[] args) {
List<StudentScore> list = new ArrayList<>();
list.add(new StudentScore(1, "chinese", 110));
list.add(new StudentScore(1, "english", 120));
list.add(new StudentScore(1, "math", 135));
list.add(new StudentScore(2, "chinese", 99));
list.add(new StudentScore(2, "english", 100));
list.add(new StudentScore(2, "math", 133));
list.add(new StudentScore(3, "chinese", 88));
list.add(new StudentScore(3, "english", 140));
list.add(new StudentScore(3, "math", 90));
list.add(new StudentScore(4, "chinese", 108));
list.add(new StudentScore(4, "english", 123));
list.add(new StudentScore(4, "math", 114));
list.add(new StudentScore(5, "chinese", 116));
list.add(new StudentScore(5, "english", 133));
list.add(new StudentScore(5, "math", 135)); System.out.println(sum1(list));
System.out.println(sum2(list));
}
//传统写法
public static Map<Integer, Integer> sum1(List<StudentScore> list) {
Map<Integer, Integer> map = new HashMap<>();
for (StudentScore studentScore : list) {
if (map.containsKey(studentScore.getSid())) {
map.put(studentScore.getSid(),
map.get(studentScore.getSid()) + studentScore.getScore());
} else {
map.put(studentScore.getSid(), studentScore.getScore());
}
}
return map;
} //merger写法
public static Map<Integer, Integer> sum2(List<StudentScore> list) {
Map<Integer, Integer> map = new HashMap<>();
list.stream().forEach(studentScore -> map.merge(studentScore.getSid()
, studentScore.getScore(), Integer::sum));
return map;
}
} //输出结果

{1=365, 2=332, 3=318, 4=345, 5=384}
{1=365, 2=332, 3=318, 4=345, 5=384}

3.总结

  merger方法使用起来确实在一定程度上减少了代码量,使得代码更加简洁。可见,java8新增的函数是编程确实能让我们少些点模板代码,更加关注与业务实现。

注意:本文仅代表个人理解和看法哟!和本人所在公司和团体无任何关系!

jdk8中map新增的merge方法介绍的更多相关文章

  1. C++中内存泄漏的检测方法介绍

    C++中内存泄漏的检测方法介绍 首先我们需要知道程序有没有内存泄露,然后定位到底是哪行代码出现内存泄露了,这样才能将其修复. 最简单的方法当然是借助于专业的检测工具,比较有名如BoundsCheck, ...

  2. 游戏引擎中三大及时光照渲染方法介绍(以unity3d为例)

    (转)游戏引擎中三大及时光照渲染方法介绍(以unity3d为例)   重要:在目前市面上常见的游戏引擎中,主要采用以下三种灯光实现方式: 顶点照明渲染路径细节 Vertex Lit Rendering ...

  3. SQL Server中解决死锁的新方法介绍

    SQL Server中解决死锁的新方法介绍 数据库操作的死锁是不可避免的,本文并不打算讨论死锁如何产生,重点在于解决死锁,通过SQL Server 2005, 现在似乎有了一种新的解决办法. 将下面的 ...

  4. Java集合中Map接口的使用方法

    Map接口 Map提供了一种映射关系,其中的元素是以键值对(key-value)的形式存储的,能够实现根据key快速查找value: Map中的键值对以Entry类型的对象实例形式存在: 建(key值 ...

  5. ASP.net中导出Excel的简单方法介绍

    下面介绍一种ASP.net中导出Excel的简单方法 先上代码:前台代码如下(这是自己项目里面写的一点代码先贴出来吧) <div id="export" runat=&quo ...

  6. java中遍历map的几种方法介绍

          喜欢用Java写程序的朋友都知道,我们常用的一种数据结构map中存储的是键值对,我们一般存储的方式是: map.put(key, value); 而提取相应键的值用的方法是: map.ge ...

  7. PS中抠图的四种方法介绍

    工具/原料 photoshop 软件(我用的是photoshop cc) 需要抠图的图片 开始的步骤 打开ps 打开图片,ctrl+O 魔棒抠图法 对于前景和后景有明显差别的图片用魔棒抠图法抠图比较容 ...

  8. Jenkins中构建Testcomplete项目的方法介绍

    Jenkins的部署在上一篇随笔中已经和大家介绍了,下面我们介绍一下再Jenkins中构建testcomplete项目.我这里使用的是Testcomplete11,下面详细介绍一下构建步骤. 1.Je ...

  9. ES6中函数新增的方式方法

    ---恢复内容开始---   绪 言 ES6 大家对JavaScript中的函数都不陌生.今天我就为大家带来ES6中关于函数的一些扩展方式和方法. 1.1函数形参的默认值 1.1.1基本用法 ES6 ...

随机推荐

  1. InnoDB B树 锁

    InnoDB B树 叶子=>主键+数记录非叶子=>主键1+主键3...主键4 事务和行锁 索引项加锁 相等条件来访问更新数据,避免使用范围条件 (1)InnoDB的行销是基于索引实现的,如 ...

  2. goland 实用键

    代码补全 option + command + v

  3. JAVA计算整数的位数

    /** * 计算整数的位数 * @param x * @return */ public static int countIntegerLength(int x){ final int [] size ...

  4. 使用JMail发送邮件

    使用JMail做最简单的文本邮件发送: 第一步.下载JMail和JAF 第二步.解压放到本地classpath中 第三步.使用: public class MailService{    privat ...

  5. C# JavaScriptSerializer 自定义序列化

    虽然,我个人建议使用Json.Net. 但大家需求不同.遇到一个朋友,他有个需求JavaScriptSerializer并且序列化时,隐藏基类成员. 这里我采用自定义序列化来实现: public st ...

  6. 牛客练习赛48 C,D,E

    C 小w的糖果 题意:3种操作,第一种是使pos右边的数全部+1,第二种是pos右边的数依次+k(k从1开始递增),第三种是pos右边的数依次+k^2(k从1开始递增). 解法:第一种我们很容易想到差 ...

  7. C#排序 转

    本文链接:https://blog.csdn.net/fysuccess/article/details/36416255 C#中List<T>排序的两种方法 List<Studen ...

  8. 安装docker-ce与卸载(centos 7)

    1.安装依赖 docker依赖于系统的一些必要的工具,可以提前安装. 1 yum install -y yum-utils device-mapper-persistent-data lvm2 2.添 ...

  9. python入门学习一

    本文用来记录学习python过程中所遇到的不同的或者记忆不清的一些定义. 注释 注释用# #此处是注释 n = 123 f = 456 不转义 Python中r‘  ’表示字符串默认不转义 print ...

  10. vmware下搭建openwrt

    最近闲来无事,想研究下openwrt, 所以尝试着自己搭建一个来玩玩, 当然这里不是以源码编译的形式,那样太耗时. 首先官网下载已有的系统image,  路径如下 : https://archive. ...