Map.getOrDefault()方法


最長和諧子序列中有用到getOrDefault()方法記錄一下

default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }

這是源碼,意思就是當Map集合中有這個key時,就使用這個key值,如果沒有就使用默認值defaultValue

下面就具體的例子,再說明一下:

public class Demo13 {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("name", "lxj");
        map.put("age", "24");
        map.put("sex", "女");
        String name = map.getOrDefault("name", "test");
        System.out.println(name);// lxj,map中存在name,獲得name對應的value
        String address = map.getOrDefault("address", "北京");
        System.out.println(address);// 北京,map中不存在address,使用默認值“北京”
    }
}
明。
原文鏈接:https://blog.csdn.net/lxj_1993/java/article/details/79798963


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM