getOrDefault(Object, V): This method is available in java.util.HashMap class of Java.
Syntax:
V java.util.HashMap.getOrDefault(Object key, V defaultValue)
This method takes two arguments. This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
Parameters: Two parameters are required for this method.
key: the key whose associated value is to be returned.
defaultValue: the default mapping of the key.
Returns: the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
Exceptions: NA
Approach
Java
import java.util.HashMap;public class HashMapgetOrDefault {public static void main(String[] args) {HashMap<String, Integer> hashMap =new HashMap<String, Integer>();hashMap.put("Hello", 1);hashMap.put("World", 2);Object key = "Java";System.out.println(hashMap.getOrDefault(key, 10));}}
Output:
10
No comments:
Post a Comment