In this tutorial we will learn how to use getOrDefault method in Java.
Introduction
getOrDefault is present in Map interface to get value for a given key and return a default value
if the key is not present.
It helps to prevent NullPointerException when retrieving values from the Map.
Below is snippet code of getOrDefault
1
2
3
4
5
6
default V getOrDefault ( Object key , V defaultValue ) {
V v ;
return ((( v = get ( key )) != null ) || containsKey ( key ))
? v
: defaultValue ;
}
In the below example we get null as return value if the key is not present.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package examples ;
import java.util.HashMap ;
import java.util.Map ;
public class App {
public static void main ( String [] args ) {
Map < String , Integer > data = new HashMap <>();
data . put ( "Sydney" , 200 );
data . put ( "Tokyo" , 300 );
System . out . println ( data . get ( "Paris" )); // null
}
}
To avoid this we can use getOrDefault which returns the default value as 0 if the key is not present.
This helps us to avoid writing extra check for null values.
If the key is present it return the corresponding value as shown below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package examples ;
import java.util.HashMap ;
import java.util.Map ;
public class App {
public static void main ( String [] args ) {
Map < String , Integer > data = new HashMap <>();
data . put ( "Sydney" , 200 );
data . put ( "Tokyo" , 300 );
System . out . println ( data . getOrDefault ( "Paris" , 0 )); // 0
System . out . println ( data . getOrDefault ( "Sydney" , 0 )); //200
}
}
Use Case
In the below use case we can use getOrDefault to provide default message/response when the key is
not present.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package examples ;
import java.util.HashMap ;
import java.util.Map ;
public class App {
public static void main ( String [] args ) {
Map < Integer , String > data = new HashMap <>();
data . put ( 404 , "Not Found" );
data . put ( 403 , "Forbidden" );
int errorCode = 600 ;
System . out . println ( data . getOrDefault ( errorCode , "Unknown Error" ));
//Unknown Error
}
}
Conclusion
getOrDefault method simplifies getting key and default value handling.
Prevents NullPointerException by returning default value.
It is helpful in providing default message/reponse for a given key.