Map.getOrDefault(Object, V)
Map的新方法getOrDefault(Object,V)允许调用者在代码语句中规定获得在map中符合提供的键的值,否则在没有找到提供的键的匹配项的时候返回一个“默认值”。
使用一串测试数组:
{3,1,4,1,5}
代码如下:
public static Map<Integer,Integer> countNum(int[] nums){
Map<Integer,Integer> map = new HashMap<>();
for (int num : nums){
map.put(num,map.getOrDefault(num,0) + 1);
}
return map;
}