Java Map

merge()用法初试

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

1、初始化数据

  1. private List<StudentScore> buildATestList() {
  2. List<StudentScore> studentScoreList = new ArrayList<>();
  3. StudentScore studentScore1 = new StudentScore() {{
  4. setStuName("张三");
  5. setSubject("语文");
  6. setScore(70);
  7. }};
  8. StudentScore studentScore2 = new StudentScore() {{
  9. setStuName("张三");
  10. setSubject("数学");
  11. setScore(80);
  12. }};
  13. StudentScore studentScore3 = new StudentScore() {{
  14. setStuName("张三");
  15. setSubject("英语");
  16. setScore(65);
  17. }};
  18. StudentScore studentScore4 = new StudentScore() {{
  19. setStuName("李四");
  20. setSubject("语文");
  21. setScore(68);
  22. }};
  23. StudentScore studentScore5 = new StudentScore() {{
  24. setStuName("李四");
  25. setSubject("数学");
  26. setScore(70);
  27. }};
  28. StudentScore studentScore6 = new StudentScore() {{
  29. setStuName("李四");
  30. setSubject("英语");
  31. setScore(90);
  32. }};
  33. StudentScore studentScore7 = new StudentScore() {{
  34. setStuName("王五");
  35. setSubject("语文");
  36. setScore(80);
  37. }};
  38. StudentScore studentScore8 = new StudentScore() {{
  39. setStuName("王五");
  40. setSubject("数学");
  41. setScore(85);
  42. }};
  43. StudentScore studentScore9 = new StudentScore() {{
  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. return studentScoreList;
  58. }

2、常规的分组计算

  1. ObjectMapper objectMapper = new ObjectMapper();
  2. List<StudentScore> studentScoreList = buildATestList();
  3. Map<String, Integer> studentScoreMap = new HashMap<>();
  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}

3、merge()的分组计算

  1. Map<String, Integer> studentScoreMap2 = new HashMap<>();
  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. default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
  2. Objects.requireNonNull(remappingFunction);
  3. Objects.requireNonNull(value);
  4. V oldValue = this.get(key);
  5. V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
  6. if (newValue == null) {
  7. this.remove(key);
  8. } else {
  9. this.put(key, newValue);
  10. }
  11. return newValue;
  12. }

可以看到原理也是很简单的,该方法接收三个参数,一个 key 值,一个 value,一个 remappingFunction ,如果给定的key不存在,它就变成了 put(key, value)
但是,如果 key 已经存在一些值,remappingFunction 可以选择合并的方式,然后将合并得到的 newValue 赋值给原先的 key。

使用场景

这个使用场景相对来说还是比较多的,比如分组求和这类的操作,虽然 stream 中有相关 groupingBy() 方法,但如果想在循环中做一些其他操作的时候,merge() 还是一个挺不错的选择的。

其他

除了 merge() 方法之外,Java 8 中 map 相关的其他方法,比如 putIfAbsentcompute()computeIfAbsent()computeIfPresent,这些方法看名字应该就知道是什么意思了,这里贴一下 compute()(Map.class) 的源码,其返回值是计算后得到的新值:

  1. default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  2. Objects.requireNonNull(remappingFunction);
  3. V oldValue = this.get(key);
  4. V newValue = remappingFunction.apply(key, oldValue);
  5. if (newValue == null) {
  6. if (oldValue == null && !this.containsKey(key)) {
  7. return null;
  8. } else {
  9. this.remove(key);
  10. return null;
  11. }
  12. } else {
  13. this.put(key, newValue);
  14. return newValue;
  15. }
  16. }