getOrDefault()
函数作用
getOrDefault() 方法获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值。
函数原型
hashmap.getOrDefault(Object key, V defaultValue)
参数说明:
- key :键
- defaultValue :当指定的key并不存在映射关系中,则返回的该默认值
返回值:
- 返回 key 相映射的的 value,如果给定的 key 在映射关系中找不到,则返回指定的默认值。
代码案例
import java.util.HashMap; class Main { public static void main(String[] args) { // 创建一个 HashMap HashMap<Integer, String> sites = new HashMap<>(); // 往 HashMap 添加一些元素 sites.put(1, "Google"); sites.put(2, "Runoob"); sites.put(3, "Taobao"); System.out.println("sites HashMap: " + sites); // key 的映射存在于 HashMap 中 // Not Found - 如果 HashMap 中没有该 key,则返回默认值 String value1 = sites.getOrDefault(1, "Not Found"); System.out.println("Value for key 1: " + value1); // key 的映射不存在于 HashMap 中 // Not Found - 如果 HashMap 中没有该 key,则返回默认值 String value2 = sites.getOrDefault(4, "Not Found"); System.out.println("Value for key 4: " + value2); } }
运行结果:
LeetCode题应用
题目链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
题解:
直接哈希
class Solution { public int firstUniqChar(String s) { Map<Character, Integer> frequency = new HashMap<Character, Integer>(); for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); // 能找到给value+1 , 找不到置为默认值0 frequency.put(ch, frequency.getOrDefault(ch, 0) + 1); } for (int i = 0; i < s.length(); ++i) { if (frequency.get(s.charAt(i)) == 1) { return i; } } return -1; } }