HashMap to return default value for non-found keys?

后端 未结 14 2256
别跟我提以往
别跟我提以往 2020-11-27 14:05

Is it possible to have a HashMap return a default value for all keys that are not found in the set?

14条回答
  •  广开言路
    2020-11-27 14:24

    Can't you just create a static method that does exactly this?

    private static  V getOrDefault(Map map, K key, V defaultValue) {
        return map.containsKey(key) ? map.get(key) : defaultValue;
    }
    

提交回复
热议问题