java.util.HashMap getOrDefault()

Description

On this document we will be showing a java example on how to use the getOrDefault() method of HashMap Class. Basically this method is to return a default value whenever the value was not found using the key specified on the HashMap. This is a convenient way to handle the scenario where we want a returned other than null which is being returned by get method whenever the key was not found on the HashMap object.

In dealing with HashMap methods, as a general rule you must always watch out for Generics such that if we have declared our map like HashMap<Integer,String> map = new HashMap<Integer,String>();  then the returned keys are expected to be Integer object type or its subclass and the values as String.

Important notes for getOrDefault () method:

  •  specified by getOrDefault in interface Map<K,V>

Method Syntax

public V getOrDefault(Object key,V defaultValue)

Method Argument

Data Type Parameter Description
Object Key key the key whose associated value is to be returned
V defaultValue the default mapping of the key

Method Returns

The getOrDefault() method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Compatibility

Requires Java 1.2 and up

Java HashMap getOrDefault() Example

Below is a java code demonstrates the use of getOrDefault() method of HashMap class. The example presented might be simple however it shows the behavior of the getOrDefault() method.

package com.javatutorialhq.java.examples;

import java.util.HashMap;

/*
 * This example source code demonstrates the use of  
 * getOrDefault() method of HashMap class
 */

public class HashMapGetOrDefaultExample {

	public static void main(String[] args) throws InterruptedException {

		int idNum = 9756;
		HashMap<Integer, String> map = init();
		System.out.println("Student with id number " + idNum + " is "
				+ map.getOrDefault(idNum, "John Doe"));

	}

	private static HashMap<Integer, String> init() {
		// declare the hashmap
		HashMap<Integer, String> mapStudent = new HashMap<>();
		// put contents to our HashMap
		mapStudent.put(73654, "Shyra Travis");
		mapStudent.put(98712, "Sharon Wallace");
		return mapStudent;
	}

}

This example is a lot simpler than it looks. First we have a method init() which generally populates a HashMap object and returned. This method has been called by the main method and used the getOrDefault to display the student name based on the student id input argument.The default student name is John Doe which will always be displayed whenever the student id was not found on the student database.

Sample Output

Below is the sample output when you run the above example.

HashMap getOrDefault() method example