天天看点

JAVA8 Map新方法:compute,computeIfAbsent,putIfAbsent与put的区别

不管存不存在key,都设值:

1. put

put返回旧值,如果没有则返回null

@Test

public void testMap() {

Map<String, String> map = new HashMap<>();

map.put("a","A");

map.put("b","B");

String v = map.put("b","v"); // 输出 B

System.out.println(v);

String v1 = map.put("c","v");

System.out.println(v1); // 输出:NULL

}

1

2

3

4

5

6

7

8

9

10

2. compute(相当于put,只不过返回的是新值)

compute:返回新值

当key不存在时,执行value计算方法,计算value

map.put("a", "A");

map.put("b", "B");

String val = map.compute("b", (k, v) -> "v"); // 输出 v

System.out.println(val);

String v1 = map.compute("c", (k, v) -> "v"); // 输出 v

System.out.println(v1);

11

12

以下几个方法,如果不存在,再put:

1. putIfAbsent

putIfAbsent返回旧值,如果没有则返回null

先计算value,再判断key是否存在

String v = map.putIfAbsent("b","v"); // 输出 B

String v1 = map.putIfAbsent("c","v"); // 输出 null

2. computeIfAbsent

computeIfAbsent:存在时返回存在的值,不存在时返回新值

参数为:key,value计算方法

String v = map.computeIfAbsent("b",k->"v"); // 输出 B

String v1 = map.computeIfAbsent("c",k->"v"); // 输出 v

————————————————

版权声明:本文为CSDN博主「衣冠の禽兽」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/wang_8101/article/details/82191146