java 8 Map api 学习

Map<String, String> map = new HashMap<>();
map.put("aa", "1");
map.put("bb", null);

1. compute (运算\消费)map中的某对值java

for (String item : map.keySet()) {
            System.out.println(map.compute(item, (key, val) -> key + "=" + val.toString()));
        }

结果:map中全部的值都参与计算。因此会出现空指针web

aa=1
Exception in thread "main" java.lang.NullPointerException
	at com.xy.pay.web.interceptor.AliPayNotifyInterceptor.lambda$main$0(AliPayNotifyInterceptor.java:48)
	at java.util.HashMap.compute(HashMap.java:1196)
	at com.xy.pay.web.interceptor.AliPayNotifyInterceptor.main(AliPayNotifyInterceptor.java:48)

 

2.computeIfPresent指针

for (String item : map.keySet()) {
            System.out.println(map.computeIfPresent(item, (key, val) -> key + "=" + val.toString()));
        }

结果:map 中value 为空的值,不会参与运算。(不会产生空指针)code

aa=1
null

 

3.computeIfAbsentrem

System.out.println(map.computeIfAbsent("aa", (key) -> "key is " + key.toString()));
//结果1:1

 System.out.println(map.computeIfAbsent("cc", (key) -> "key is " + key.toString()));
//结果2: key is cc

说明:根据 key 判断其value是否有值,若是为nul则运算 lambda表达式 (结果2),不然返回其值(结果1)get

 

4. putIfAbsent  若是当前容器中的值为 null 那么就 执行 put操做。不然不操做it

 

5.  getOrDefault  若是为空,返回默认值io

 

6. mergeclass

//1.使用值"2"去替换原来的值,若是原来的值为空,则直接替换。不然使用lambda表达式的值
//2.若是替换的值为null,则执行remove 操做 
//3.返回替换的值
map.merge("bb", "2", (oldVal, newVal) -> newVal);

结果: “bb” = "2"thread

相关文章
相关标签/搜索