java 8 Map api 学习

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

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

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

结果:map中所有的值都参与计算。所以会出现空指针

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 为空的值,不会参与运算。(不会产生空指针)

aa=1
null

3.computeIfAbsent

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)

4. putIfAbsent  如果当前容器中的值为 null 那么就 执行 put操作。否则不操作

5.  getOrDefault  如果为空,返回默认值

6. merge

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

结果: “bb” = "2"

猜你喜欢

转载自my.oschina.net/u/2552286/blog/1814641