HashMap的getOrDefault()方法

HashMap的getOrDefault()方法

    /**
     * Created by 谭健 2017/8/24. 21:42.
     * All Rights Reserved
     */
    public static void main(String[] args) {
        HashMap hashMap = new HashMap<>();
        hashMap.putIfAbsent("orderId", "20170824222735412201");
        hashMap.putIfAbsent("userId","1012758623");
        hashMap.putIfAbsent("mobilePhone", "15197447018");
        hashMap.getOrDefault("orderId", "19700000000000000000");
        hashMap.getOrDefault("userId", "1000000000");
        hashMap.getOrDefault("mobilePhone", "10000000000");
        // old
        if (hashMap.containsKey("orderId")) {
            String orderId = (String) hashMap.get("orderId");
            if (null == orderId || "".equals(orderId)) {
                orderId = "19700000000000000000";
            }
        }
    }

- 相较于原来的写法,新的getOrDefault()方法提供一个快捷的方式获取Map中的值

- 他的代码量更少,并且更具有可读性

- 应该推荐getOrDefault()这种写法,他为我们提供了一个更加可靠的代码体验

你可能感兴趣的:(#,底层实现,/,性能优化,/,安全)