关于java:Java-8-中-Map-骚操作好用到爆

27次阅读

共计 3875 个字符,预计需要花费 10 分钟才能阅读完成。

作者:lq 木头 \
链接:https://juejin.cn/post/684490…

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 相干的其余办法,比方 putIfAbsentcompute()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() 同理。所以,源码必定是要看的,不懂的中央多读多练天然就了解了。

近期热文举荐:

1.1,000+ 道 Java 面试题及答案整顿 (2022 最新版)

2. 劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4. 别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

正文完
 0