Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
hashmap
getordefault
communitycreator

What is the getOrDefault method of HashMap in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The getOrDefault(key, defaultVaule) method of HashMap will:

  • Return Default Value if there is no mapping for the passed key.

  • Return the value mapped to the key if there is a mapping present for the passed key.

Syntax

hashMap.getOrDefalt(key, defauulutValue);

Example

import java.util.HashMap;
class DefaulutVaue {
public static void main(String[] args) {
// create an HashMap
HashMap<Integer, String> numbers = new HashMap<>();
numbers.put(1, "One");
numbers.put(2, "Two");
numbers.put(3, "Three");
System.out.println("The HashMap is - " + numbers);
System.out.println("Getting value for key 5 using get(5) Method" );
System.out.println(numbers.get(5));
System.out.println("Getting value for key 5 using getOrDefault(5, 'Default Value') Method" );
System.out.println(numbers.getOrDefault(5, "Default value"));
System.out.println("Getting value for key 1 using getOrDefault Method" );
System.out.println(numbers.getOrDefault(1, "Default value"));
}
}

In the code above, we have:

  • Created a HashMap with name numbers.

  • Added three entries to the numbers HashMap.

  • Called the get method for the key 5. This will return null because there is no value mapping for the key 5.

  • Called the getOrDefault(5, "Default Value") method. This will return “Default Value” because there is no value mapped for the key 5, so the default value return passed.

  • Called the getOrDefault(1, "Default Value") method. This will return “One” because the value One is mapped for the key 1.


For example, say we have a mapping for users with images. If the image for the user is not present, then it returns the default user image. Cases like this can be handled with the getOrDefault method.

Use the getOrDefault method when you need a default value if the value is not present in the HashMap.

RELATED TAGS

java
hashmap
getordefault
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring