What is the LinkedHashMap.getOrDefault method in Java?
A LinkedHashMap is the same as a HashMap, except the LinkedHashMap maintains the insertion order, whereas the HashMap doesn’t. Internally, the LinkedHashMap uses a doubly-linked list to maintain the insertion order.
Syntax
public V getOrDefault(Object key,V defaultValue)
Parameters
key: Key whose value is to be returned.defaultValue: Default mapping of key.
Return value
-
Returns
Default Valueif there is no mapping for the passedkey. -
Returns the value mapped to the
keyif there is a mapping present for the passedkey.
Code
The code below demonstrates how to use the getOrDefault method.
import java.util.LinkedHashMap;class DefaultVaue {public static void main(String[] args) {// create an LinkedHashMapLinkedHashMap<Integer, String> numbers = new LinkedHashMap<>();numbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");System.out.println("The LinkedHashMap is - " + numbers);System.out.print("\nGetting value for key 5 using get(5) Method :" );System.out.println(numbers.get(5));System.out.print("\nGetting value for key 5 using getOrDefault(5, 'Default Value') Method :" );System.out.println(numbers.getOrDefault(5, "Default value"));System.out.print("\nGetting value for key 1 using getOrDefault Method :" );System.out.println(numbers.getOrDefault(1, "Default value"));}}
In the code above, we:
-
Created a
LinkedHashMapwith the namenumbers. -
Added three entries to the
numbers. -
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 returnDefault Valuebecause there is no value mapped for the key5, so the default value return is passed. -
Called the
getOrDefault(1, "Default Value")method. This will returnOnebecause 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 theLinkedHashMap.