1、基本API

2、merge

2.1 用法

map.mergejdk8新增的特性,总的来说是在map里put k-v时的优化,在对应场景下可以少写代码,源码如下:

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

merge方法接收3个参数:

  • key:map的key;
  • value:map的value;
  • remappingFunction:BiFunction函数接口,该接口接收两个值,执行自定义功能并返回最终值。

merge方法是向map里put k-v,当map里不存在第一个入参的key时,直接将第二个入参value和第一个入参组成key-value put进map里;当map里存在第一个入参的key时,将map里key对应的value值和第二个入参value执行remappingFunction里自定义的处理方法,返回值与第一个入参key组成新的k-v put进map里。

2.2 举例

比如我有一些学生的信息:

  • 学生姓名;
  • 课程名称;
  • 课程成绩。

我想统计每个学生所有课程成绩的总得分,如下:

学生类:

package com.Jerry.map;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Student {
    private String name;
    private String courseName;
    private int score;
}

merge使用:

package com.Jerry.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapMergeMain {
    public static void main(String[] args) {
        // 构造学生成绩数据
        List<Student> studentList = new ArrayList<Student>();
        studentList.add(new Student("Jerry", "Math", 100));
        studentList.add(new Student("Cissie", "English", 95));
        studentList.add(new Student("Tom", "Science", 100));
        studentList.add(new Student("Tom", "Math", 90));
        studentList.add(new Student("Jerry", "Science", 100));
        studentList.add(new Student("Jerry", "Math", 100));
        studentList.add(new Student("Cissie", "Math", 90));
        studentList.add(new Student("Tom", "Dance", 100));
        studentList.add(new Student("Jerry", "English", 100));

        System.out.println("使用map的put方法");
        System.out.println(mapPutMethod(studentList));

        System.out.println("使用map的merge方法");
        System.out.println(mapMergeMethod(studentList));
    }

    public static Map<String, Integer> mapPutMethod(List<Student> studentList)
    {
        Map<String, Integer> scoreMap = new HashMap<>();

        studentList.forEach(student -> {
            String studentName = student.getName();
            if (scoreMap.containsKey(studentName))
            {
                scoreMap.put(studentName, scoreMap.get(studentName) + student.getScore());
            }
            else
            {
                scoreMap.put(studentName, student.getScore());
            }
        });

        return scoreMap;
    }

    public static Map<String, Integer> mapMergeMethod(List<Student> studentList)
    {
        // map的key是学生姓名,value是学生总成绩
        Map<String, Integer> scoreMap = new HashMap<>();

        // 这里Integer::sum 等价于(oldValue, newValue) -> (oldValue + newValue)
        // 即将该学生已存在的分数总和与当前成绩得分相加
        studentList.forEach(student -> {
            scoreMap.merge(student.getName(), student.getScore(), Integer::sum);
        });

        return scoreMap;
    }
}

3、putIfAbsent

3.1 用法

putIfAbsent是map的put方法的一个小改动,源码如下:

default V putIfAbsent(K key, V value) {
    V v = get(key);
    if (v == null) {
        v = put(key, value);
    }

    return v;
}

map的put方法,如果key已经存在,则会覆盖之前的value。map的putIfAbsent方法,如果put的k-v,key不存在,则直接put进去,如果key已经存在,不会覆盖之前的value,而是将之前的value返回。

3.2 举例

package com.Jerry.map;

import java.util.HashMap;
import java.util.Map;

public class MapPutIfAbsentMain {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Jerry", 1);
        map.put("Tom", 2);
        map.put("Cissie", 3);
        // map.put("Jerry", 4);
        System.out.println(map.putIfAbsent("Jerry", 4));

        System.out.println(map);
    }
}

4、putAll

4.1 用法

putAll方法可以合并两个map,当遇到相同的key时,用后面的value覆盖前面的value。

4.2 举例

package com.Jerry.map;

import java.util.HashMap;
import java.util.Map;

public class MapPutAllMain {
    public static void main(String[] args) {
        // 构造数据
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("Jerry", 1);
        map1.put("Tom", 2);
        map1.put("Cissie", 3);

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("Jerry", 3);
        map2.put("Tom", 1);
        map2.put("Cissie", 3);

        map1.putAll(map2);
        System.out.println(map1);
    }
}

参考:

jdk8中map新增的merge方法介绍