Map中的put、compute、putIfAbsent、 computeIfAbsent方法的区别

1. put方法

put覆盖并返回旧值,如果不存在则返回null

public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("a","A");
        map.put("b","B");
        String v = map.put("b","v");
        System.out.println(v);// 输出 B
        String v1 = map.put("c","v");
        System.out.println(v1); // 输出:NULL
    }

 

2. compute方法

相当于put方法,不过返回的是新值。当key不存在时,执行value计算方法,计算value

public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("a", "A");
        map.put("b", "B");
        String b = map.compute("b", (k, v) -> "ss");
        System.out.println(b);//输出ss
        String b1 = map.compute("c", (k, v) -> "ss");
        System.out.println(b1);//输出ss
    }

 

3. putIfAbsent方法

如果存在则不设值,并且返回旧值。如果不存在则设值,并返回null

public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("a", "A");
        map.put("b", "B");
        String s = map.putIfAbsent("b", "ss");
        System.out.println(s);//输出B
        String s1 = map.putIfAbsent("c", "ss");
        System.out.println(s1);//输出null
    }

4. computeIfAbsent方法

如果存在则不设值,并且返回旧值。如果不存在则返回新值

Map map = new HashMap<>();
        map.put("a", "A");
        map.put("b", "B");
        String b = map.computeIfAbsent("b", k -> "v");
        System.out.println(b);//B
        System.out.println(map.get("b"));//B
        String c = map.computeIfAbsent("c", k -> "v");
        System.out.println(c);//v

 

你可能感兴趣的:(java基础)