What is the getOrDefault method of HashMap in Java?
The getOrDefault(key, defaultVaule) method of HashMap will:
-
Return
Default Valueif there is no mapping for the passedkey. -
Return the value mapped to the key if there is a mapping present for the passed
key.
Syntax
hashMap.getOrDefalt(key, defauulutValue);
Example
import java.util.HashMap;class DefaulutVaue {public static void main(String[] args) {// create an HashMapHashMap<Integer, String> numbers = new HashMap<>();numbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");System.out.println("The HashMap is - " + numbers);System.out.println("Getting value for key 5 using get(5) Method" );System.out.println(numbers.get(5));System.out.println("Getting value for key 5 using getOrDefault(5, 'Default Value') Method" );System.out.println(numbers.getOrDefault(5, "Default value"));System.out.println("Getting value for key 1 using getOrDefault Method" );System.out.println(numbers.getOrDefault(1, "Default value"));}}
In the code above, we have:
-
Created a HashMap with name
numbers. -
Added three entries to the
numbersHashMap. -
Called the
getmethod for the key5. This will returnnullbecause there is no value mapping for the key5. -
Called the
getOrDefault(5, "Default Value")method. This will return “Default Value” because there is no value mapped for the key5, so the default value return passed. -
Called the
getOrDefault(1, "Default Value")method. This will return “One” because the valueOneis mapped for the key1.
For example, say we have a mapping for users with images. If the image for the user is not present, then it returns the default user image. Cases like this can be handled with the getOrDefault method.
Use the
getOrDefaultmethod when you need a default value if the value is not present in the HashMap.