getOrDefault() 方法获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值。
getOrDefault() 方法的语法为:
hashmap.getOrDefault(Object key, V defaultValue)
这个可以怎么用呢?
举个例子:
对字符串里面的字符分别进行计数,一般平常写的就是:
public static MapcountCharacter(String s){ Map map = new HashMap<>(); for(int i = 0;i < s.length();i++){ if(map.containsKey(s.charAt(i))){ map.put(s.charAt(i), map.get(s.charAt(i)) + 1); }else{ map.put(s.charAt(i), 1); } } return map; }
但是用了这个方法以后就可以改变写法:
public MapcountCharacter(String s){ Map map = new HashMap<>(); for(int i = 0;i < s.length();i++){ int val = map.getOrDefault(s.charAt(i), 0) + 1; map.put(s.charAt(i), val); } return map; }
或者直接写为一行
public MapcountCharacter(String s){ Map map = new HashMap<>(); for(int i = 0;i < s.length();i++){ map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); } return map; }
秒啊!



