Java Map getOrDefault() Example
February 12, 2020
The getOrDefault
is the default method of java.util.Map
and has been introduced in Java 8. The getOrDefault
method returns the value for the given key and if there is no value associated with that key then the specified default value is returned. Find the method signature.
default V getOrDefault(Object key, V defaultValue)
defaultValue is the default value.
Return value is a value associated with key and if absent then default value is the return value.
Example-1
In this example, we are usingHashMap
.
GetOrDefault1.java
import java.util.HashMap; import java.util.Map; public class GetOrDefault1 { public static void main(String[] args) { Map<Integer, String> studentMap = new HashMap<>(); studentMap.put(101, "Mahesh"); studentMap.put(102, "Suresh"); studentMap.put(103, "Krishna"); String defaultValue = "No Student"; String stdName = studentMap.getOrDefault(102, defaultValue); System.out.println(stdName); stdName = studentMap.getOrDefault(104, defaultValue); System.out.println(stdName); stdName = studentMap.getOrDefault(105, defaultValue); System.out.println(stdName); } }
Suresh No Student No Student
Map
, so we get that value. For the key 104 and 105, there is no associated value and hence we will get specified default value.
Example-2
In this example, we are usingLinkedHashMap
.
GetOrDefault2.java
import java.util.LinkedHashMap; import java.util.Map; public class GetOrDefault2 { public static void main(String[] args) { Map<Integer, Integer> numberMap = new LinkedHashMap<>(); numberMap.put(1, 100); numberMap.put(2, 200); numberMap.put(3, 300); Integer defaultValue = 0; Integer val = numberMap.getOrDefault(2, defaultValue); System.out.println(val); val = numberMap.getOrDefault(6, defaultValue); System.out.println(val); val = numberMap.getOrDefault(7, defaultValue); System.out.println(val); } }
200 0 0
Example-3
In this example, we are usingTreeMap
.
GetOrDefault3.java
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; public class GetOrDefault3 { public static void main(String[] args) { Map<String, List<String>> treeMap = new TreeMap<>(); treeMap.put("color", Arrays.asList("Orange", "Yellow")); treeMap.put("game", Arrays.asList("Cricket", "Hockey")); List<String> defaultValue = new ArrayList<>(); List<String> val = treeMap.getOrDefault("game", defaultValue); System.out.println(val); val = treeMap.getOrDefault("city", defaultValue); System.out.println(val); } }
[Cricket, Hockey] []