Java 8中Map骚操作之merge()的用法

Java 8 最大的特性无异于更多地面向函数,比如引入了 lambda等,可以更好地进行函数式编程。前段时间无意间发现了 map.merge() 方法,感觉还是很好用的,此文简单做一些相关介绍。 2020-04-27 20:55:42 JavaJava 8编程语言 值得期待的Python 3.9的新功能 Python 3.9 beta预计下个月就要发布了,那么3.9有那些让我们期待的新功能和变更呢?本我我们一起来说Python 3.9的新功能的。

Java 8 最大的特性无异于更多地面向函数,比如引入了 lambda等,可以更好地进行函数式编程。前段时间无意间发现了 map.merge() 方法,感觉还是很好用的,此文简单做一些相关介绍。

[[324081]]

Java 8 最大的特性无异于更多地面向函数,比如引入了 lambda等,可以更好地进行函数式编程。前段时间无意间发现了 map.merge() 方法,感觉还是很好用的,此文简单做一些相关介绍。首先我们先看一个例子。

merge() 怎么用?

假设我们有这么一段业务逻辑,我有一个学生成绩对象的列表,对象包含学生姓名、科目、科目分数三个属性,要求求得每个学生的总成绩。加入列表如下:

  1. privateList<StudentScore>buildATestList(){
  2. List<StudentScore>studentScoreList=newArrayList<>();
  3. StudentScorestudentScore1=newStudentScore(){{
  4. setStuName("张三");
  5. setSubject("语文");
  6. setScore(70);
  7. }};
  8. StudentScorestudentScore2=newStudentScore(){{
  9. setStuName("张三");
  10. setSubject("数学");
  11. setScore(80);
  12. }};
  13. StudentScorestudentScore3=newStudentScore(){{
  14. setStuName("张三");
  15. setSubject("英语");
  16. setScore(65);
  17. }};
  18. StudentScorestudentScore4=newStudentScore(){{
  19. setStuName("李四");
  20. setSubject("语文");
  21. setScore(68);
  22. }};
  23. StudentScorestudentScore5=newStudentScore(){{
  24. setStuName("李四");
  25. setSubject("数学");
  26. setScore(70);
  27. }};
  28. StudentScorestudentScore6=newStudentScore(){{
  29. setStuName("李四");
  30. setSubject("英语");
  31. setScore(90);
  32. }};
  33. StudentScorestudentScore7=newStudentScore(){{
  34. setStuName("王五");
  35. setSubject("语文");
  36. setScore(80);
  37. }};
  38. StudentScorestudentScore8=newStudentScore(){{
  39. setStuName("王五");
  40. setSubject("数学");
  41. setScore(85);
  42. }};
  43. StudentScorestudentScore9=newStudentScore(){{
  44. setStuName("王五");
  45. setSubject("英语");
  46. setScore(70);
  47. }};
  48. studentScoreList.add(studentScore1);
  49. studentScoreList.add(studentScore2);
  50. studentScoreList.add(studentScore3);
  51. studentScoreList.add(studentScore4);
  52. studentScoreList.add(studentScore5);
  53. studentScoreList.add(studentScore6);
  54. studentScoreList.add(studentScore7);
  55. studentScoreList.add(studentScore8);
  56. studentScoreList.add(studentScore9);
  57. returnstudentScoreList;
  58. }

我们先看一下常规做法:

  1. ObjectMapperobjectMapper=newObjectMapper();
  2. List<StudentScore>studentScoreList=buildATestList();
  3. Map<String,Integer>studentScoreMap=newHashMap<>();
  4. studentScoreList.forEach(studentScore->{
  5. if(studentScoreMap.containsKey(studentScore.getStuName())){
  6. studentScoreMap.put(studentScore.getStuName(),
  7. studentScoreMap.get(studentScore.getStuName())+studentScore.getScore());
  8. }else{
  9. studentScoreMap.put(studentScore.getStuName(),studentScore.getScore());
  10. }
  11. });
  12. System.out.println(objectMapper.writeValueAsString(studentScoreMap));
  13. //结果如下:
  14. //{"李四":228,"张三":215,"王五":235}

然后再看一下 merge() 是怎么做的:

  1. Map<String,Integer>studentScoreMap2=newHashMap<>();
  2. studentScoreList.forEach(studentScore->studentScoreMap2.merge(
  3. studentScore.getStuName(),
  4. studentScore.getScore(),
  5. Integer::sum));
  6. System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
  7. //结果如下:
  8. //{"李四":228,"张三":215,"王五":235}

merge() 简介

merge() 可以这么理解:它将新的值赋值到 key (如果不存在)或更新给定的key 值对应的 value,其源码如下:

  1. defaultVmerge(Kkey,Vvalue,BiFunction<?superV,?superV,?extendsV>remappingFunction){
  2. Objects.requireNonNull(remappingFunction);
  3. Objects.requireNonNull(value);
  4. VoldValue=this.get(key);
  5. VnewValue=oldValue==null?value:remappingFunction.apply(oldValue,value);
  6. if(newValue==null){
  7. this.remove(key);
  8. }else{
  9. this.put(key,newValue);
  10. }
  11. returnnewValue;
  12. }

我们可以看到原理也是很简单的,该方法接收三个参数,一个 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) 的源码,其返回值是计算后得到的新值:

  1. defaultVcompute(Kkey,BiFunction<?superK,?superV,?extendsV>remappingFunction){
  2. Objects.requireNonNull(remappingFunction);
  3. VoldValue=this.get(key);
  4. VnewValue=remappingFunction.apply(key,oldValue);
  5. if(newValue==null){
  6. if(oldValue==null&&!this.containsKey(key)){
  7. returnnull;
  8. }else{
  9. this.remove(key);
  10. returnnull;
  11. }
  12. }else{
  13. this.put(key,newValue);
  14. returnnewValue;
  15. }
  16. }

总结

本文简单介绍了一下 Map.merge() 的方法,除此之外,Java 8 中的 HashMap 实现方法使用了 TreeNode 和 红黑树,在源码阅读上可能有一点难度,不过原理上还是相似的,compute() 同理。所以,源码肯定是要看的,不懂的地方多读多练自然就理解了。

链接

参考:

https://www.jianshu.com/p/68e6b30410b0

测试代码地址:

https://github.com/lq920320/algorithm-java-test/blob/master/src/test/java/other/MapMethodsTest.java

©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经

(0)
打赏 微信扫码打赏 微信扫码打赏 支付宝扫码打赏 支付宝扫码打赏
清一色的头像清一色管理团队
上一篇 2023年5月5日 10:58
下一篇 2023年5月5日 10:58

相关推荐

发表评论

登录后才能评论

联系我们

在线咨询:1643011589-QQbutton

手机:13798586780

QQ/微信:1074760229

QQ群:551893940

工作时间:工作日9:00-18:00,节假日休息

关注微信