前段时间看某个框架源码时,看到有用到map.getOrDefault这个方法,出于好奇就简单了解了一下。
直接看一下源码还是比较简单的,传入key和一个默认值,如果key值存在就直接返回对应的value值,否则直接返回默认值。
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
具体应用
/**
* 利用map统计一个字符串中,每个字母出现的次数
*/
public class MapDemo {
public static void main(String[] args) {
//一般方法
System.out.println(method1());
//getOrDefault方法
System.out.println(method2());
}
private static Map method1() {
String str = "aabbbcccc";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
return map;
}
private static Map method2() {
String str = "aabbbcccc";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
return map;
}
}
getOrDefault是不是看起来更简洁,更装逼。。。