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. spring_AOP的注解开发

    logger日志类: package cn.mepu.utils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.la ...

  2. 最新版react16.9中按需加载antd和使用less

    使用create-react-app创建应用 yarn create react-app my-app cd my-app yarn start 引入 antd 这是 create-react-app ...

  3. teb教程3

    配置和运行机器人导航 简介:配置teb_local_planner作为navigation中local planner的插件 参考teb安装 由于局部代价地图的大小和分辨率对优化性能影响很大,因为占据 ...

  4. 前端学习(二十一)初识h5(笔记)

    html5        主要目标:语义化!可以被人或者机器更好的阅读! 支持各种媒体的嵌入!不兼容低版本!------------ html5新标签: 普通:     <header clas ...

  5. day04 python列表 元组 range()

    day04 python   一.列表 1.什么是列表     列表是可变的数据类型: 和字符串不同, 做的操作直接改源数据     列表由[]来表示, 每项元素用逗号隔开.列表什么都能装,能装对象的 ...

  6. Async Clipboard AP

    转自奇舞周刊,个人学习记录,侵权删 编者按:本文作者李松峰,资深技术图书译者,翻译出版过40余部技术及交互设计专著,现任360奇舞团高级前端开发工程师,360前端技术委员会委员.W3C AC代表 如果 ...

  7. python 装饰器的坑

    今天研究了下装饰器,添加重试功能遇到了个坑,跟大家分享一下: 代码如下: def re_try(maxtry): print locals() def wrapper(fn): print local ...

  8. vue插件安装

    百度云下载插件   https://pan.baidu.com/s/13QhPilzJa8yu3HvKCt47Pw 学习Vue.js时,Chrome浏览器安装Vue.js devtool能很方便的查看 ...

  9. 71 Serializable(序列化和反序列化)

    对象的输出流:ObjectOutputStream  把对象输出到文件存储起来,我们称作为序列化对象的输入流:ObjectInputStream   把对象从文件中读取出来,我们称作为反序列化 Obj ...

  10. 异步ajax请求数据处理

    jQuery.ajax(url,[settings]) 概述 通过 HTTP 请求加载远程数据. jQuery 底层 AJAX 实现.简单易用的高层实现见 $.get, $.post 等.$.ajax ...