Java HashMap getOrDefault() method example

HQ ┬╗ Java Tutorial ┬╗ java.util ┬╗ Hashmap ┬╗ getOrDefault() method example
Java HashMap getOrDefault() method example 2018-02-16T07:27:12+00:00

java.util.HashMap getOrDefault()


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.


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.

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

Contact Info


Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.