面试官:Java8中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;
    }
}

总结

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

作者:LQ木头 
juejin.im/post/5d9b455ae51d45782b0c1bfb

公众号“Java精选”所发表内容注明来源的,版权归原出处所有(无法查证版权的或者未注明出处的均来自网络,系转载,转载的目的在于传递更多信息,版权属于原作者。如有侵权,请联系,笔者会第一时间删除处理!
最近有很多人问,有没有读者交流群!加入方式很简单,公众号Java精选,回复“加群”,即可入群!

Java精选面试题(微信小程序):3000+道面试题,包含Java基础、并发、JVM、线程、MQ系列、Redis、Spring系列、Elasticsearch、Docker、K8s、Flink、Spark、架构设计等,在线随时刷题!
------ 特别推荐 ------
特别推荐:专注分享最前沿的技术与资讯,为弯道超车做好准备及各种开源项目与高效率软件的公众号,「大咖笔记」,专注挖掘好东西,非常值得大家关注。点击下方公众号卡片关注。

点击“阅读原文”,了解更多精彩内容!文章有帮助的话,点在看,转发吧!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值