YouTip LogoYouTip

Java Hashmap Getordefault

# Java HashMap getOrDefault() Method [![Image 3: Java HashMap](#) Java HashMap](#) The getOrDefault() method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. The syntax for the getOrDefault() method is: hashmap.getOrDefault(Object key, V defaultValue) **Note:** hashmap is an object of the HashMap class. **Parameter Description:** * key - the key whose associated value is to be returned * defaultValue - the default mapping to be returned if this map contains no mapping for the key ### Return Value Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. ### Example The following example demonstrates the use of the getOrDefault() method: ## Example import java.util.HashMap; class Main { public static void main(String[] args){ // Create a HashMap HashMap sites =new HashMap(); // Add some elements to the HashMap sites.put(1, "Google"); sites.put(2, ""); sites.put(3, "Taobao"); System.out.println("sites HashMap: "+ sites); // Key mapping exists in HashMap // Not Found - returns the default value if the key is not in the HashMap String value1 = sites.getOrDefault(1, "Not Found"); System.out.println("Value for key 1: "+ value1); // Key mapping does not exist in HashMap // Not Found - returns the default value if the key is not in the HashMap String value2 = sites.getOrDefault(4, "Not Found"); System.out.println("Value for key 4: "+ value2); } } The output of the above program is: Value for key 1: GoogleValue for key 4: Not Found **Note:** We can use the [HashMap containsKey() method](#) to check if a specific key exists in the HashMap. [![Image 4: Java HashMap](#) Java HashMap](#)
← Java Hashmap EntrysetPython3 Os Fchdir β†’