The getOrDefault
function in Java comes with the HashMap
class, and is used to find the value of a corresponding key stored inside a HashMap
object.
default V getOrDefault(Object key, V defaultValue)
The getOrDefault
function takes in two parameters:
key
: the key whose corresponding value is to be returned.
defaultValue
: value to be returned by default in case the key prescribed by the user is not present in the HashMap
object.
Upon successful execution, the getOrDefault
function returns the corresponding value of the key prescribed by the user.
If the key is not present, the
defaultValue
is returned.
The program below demonstrates how to use the getOrDefault
function. We declare a HashMap
object named countries, which stores the rank and name of the four largest countries (area wise) as key-value pairs.
Each country name is in lower case.
We use the getOrDefault
function to find the country that ranks 3 and store the return value in a String
variable named a
. Since our HashMap
stores information about the top 4 rankings only, when inquired for the country that ranks 5, the getOrDefault
function returns the default value, as 5
is not a key in any of the key-value pairs. The default value is stored in a String
value named b
.
Before terminating, the program prints the values of a
and b
using the println
function.
import java.util.HashMap;class Main {public static void main(String[] args) {System.out.println("This program ranks countries on the basis of land-area covered.");System.out.println("Each key in the HashMap is a rank and each corresponding value is a country name.");// create an HashMapHashMap<Integer, String> countries = new HashMap<>();// populate the HashMapcountries.put(1, "russia");countries.put(2, "canada");countries.put(3, "china");countries.put(4, "united states");System.out.println("**Printing HashMap**");System.out.println(countries);//Apply getOrDefault functionString a = countries.getOrDefault(3, "No entry found!");String b = countries.getOrDefault(5, "No entry found!");System.out.println("The value returned for key = 3: " + a);System.out.println("The value returned for key = 5: "+ b);}}
Free Resources