The getOrDefault(key, defaultVaule)
method of HashMap will:
Return Default Value
if there is no mapping for the passed key
.
Return the value mapped to the key if there is a mapping present for the passed key
.
hashMap.getOrDefalt(key, defauulutValue);
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 numbers
HashMap.
Called the get
method for the key 5
. This will return null
because there is no value mapping for the key 5
.
Called the getOrDefault(5, "Default Value")
method. This will return “Default Value” because there is no value mapped for the key 5
, so the default value return passed.
Called the getOrDefault(1, "Default Value")
method. This will return “One” because the value One
is mapped for the key 1
.
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
getOrDefault
method when you need a default value if the value is not present in the HashMap.