Let’s start with a simple Java program and understand:-
package Concepts; import java.util.HashMap; import java.util.Map; public class GetOrDefaultMethodExample { public static void main(String[] args) { MapdataMap = new HashMap<>(); dataMap.put(101,"Amod"); dataMap.put(102,"Swati"); dataMap.put(103,"Aaditya"); dataMap.put(104,"Animesh"); System.out.println(dataMap.get(101)); System.out.println(dataMap.get(102)); System.out.println(dataMap.get(103)); System.out.println(dataMap.get(104)); // Non-existing key in dataMap System.out.println(dataMap.get(105)); } }
Output
Amod Swati Aaditya Animesh null
I have created a Map<Integer, String> and stored some key-value pairs. When I try to get the value of existing keys then it returns as expected but when I try to get the value of non-existing keys, it returns NULL and if you try to perform any action on it then you get NullPointerException.
Map interface provides a method getOrDefault() which allows you to return a default value in case of non-existence of a key in Map. It returns the value to which the specified key is mapped, or if this map contains no mapping for the key.
You can see implementation of getOrDefault() method. It is not difficult to create such a method ourselves but it has been added in utility in Map interface for direct use. It was added in 1.8.
Let’s use above method in above program:-
package Concepts; import java.util.HashMap; import java.util.Map; public class GetOrDefaultMethodExample { public static void main(String[] args) { MapdataMap = new HashMap<>(); dataMap.put(101,"Amod"); dataMap.put(102,"Swati"); dataMap.put(103,"Aaditya"); dataMap.put(104,"Animesh"); System.out.println(dataMap.get(101)); System.out.println(dataMap.get(102)); System.out.println(dataMap.get(103)); System.out.println(dataMap.get(104)); // Non-existing key in dataMap System.out.println(dataMap.get(105)); System.out.println("==================================="); System.out.println(dataMap.getOrDefault(101, "No Name")); System.out.println(dataMap.getOrDefault(102, "No Name")); System.out.println(dataMap.getOrDefault(103, "No Name")); System.out.println(dataMap.getOrDefault(104, "No Name")); System.out.println(dataMap.getOrDefault(105, "No Name")); } }
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning
Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.
Many other topics you can navigate through the menu.