Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Return Value
5.
Programs
5.1.
Example 1: Retrieving a value from a HashMap
5.2.
Java
5.3.
Example 2: Counting occurrences of words
5.4.
Java
6.
Frequently Asked Questions
6.1.
What happens if the key passed to the getOrDefault() method is null?
6.2.
Can the default value passed to the getOrDefault() method be null?
6.3.
Is the getOrDefault() method thread-safe?
7.
Conclusion
Last Updated: Aug 4, 2024
Easy

Java Hashmap getordefault() Method

Author Ravi Khorwal
0 upvote

Introduction

The Java HashMap is a powerful data structure that allows you to store and retrieve key-value pairs efficiently. One of the useful methods provided by the HashMap class is the getOrDefault() method. This method lets you retrieve the value associated with a specific key, and if the key is not found, it returns a default value that you specify. 

Java Hashmap getordefault() Method

In this article, we will discuss its syntax, parameters, and return value, with examples.

Syntax

The syntax for the getOrDefault() method is:

public V getOrDefault(Object key, V defaultValue)


In this syntax:

- `key` represents the key whose associated value you want to retrieve from the HashMap.

- `defaultValue` is the default value that will be returned if the specified key is not found in the HashMap.

- `V` represents the type of the value associated with the key.

The getOrDefault() method is called on a HashMap object, and it takes two parameters: the key and the default value. It returns the value associated with the specified key if it exists in the HashMap, or the default value if the key is not found.

Parameters

The getOrDefault() method takes two parameters:

1. `key` (Object): The key whose associated value you want to retrieve from the HashMap. The key can be of any object type, but it should be consistent with the type of keys used in the HashMap.
 

2. `defaultValue` (V): The default value that will be returned if the specified key is not found in the HashMap. This parameter is of the same type as the values stored in the HashMap.
 

It's important to remember that the getOrDefault() method does not modify the HashMap. If the specified key is not found, it simply returns the default value without adding the key-value pair to the HashMap.

Return Value

The getOrDefault() method returns a value of type `V`, which represents the type of the values stored in the HashMap. The return value can be either one of the mentioned below:

- If the specified key is found in the HashMap, the method returns the value associated with that key.
 

- If the specified key is not found in the HashMap, the method returns the default value provided as the second parameter.
 

The returned value is always of the same type as the values stored in the HashMap. If the HashMap is empty and the specified key is not found, the method will return the default value.

Programs

Let's discuss a few example programs that show how to use the getOrDefault() method in Java.

Example 1: Retrieving a value from a HashMap

  • Java

Java

import java.util.HashMap;

public class GetOrDefaultExample1 {

   public static void main(String[] args) {

       // Create a HashMap

       HashMap<String, Integer> map = new HashMap<>();

// Add key-value pairs to the HashMap

       map.put("Rahul", 25);

       map.put("Rinki", 30);

       map.put("Harsh", 35);       

       // Retrieve values using getOrDefault()

       int age1 = map.getOrDefault("Rahul", 0);

       int age2 = map.getOrDefault("Sanjana", 0);

     System.out.println("Rahul's age: " + age1);

       System.out.println("Sanjana's age: " + age2);

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Rahul's age: 25
Sanjana's age: 0


In this example, we create a HashMap called `map` that stores the names as keys and ages as values. We add three key-value pairs to the HashMap using the `put()` method.

Then, we use the `getOrDefault()` method to retrieve the ages of "Rahul" and "Sanjana". Since "Rahul" exists in the HashMap, the method returns his age, which is 25. However, "Sanjana" is not present in the HashMap, so the method returns the default value of 0.

Example 2: Counting occurrences of words

  • Java

Java

import java.util.HashMap;

public class GetOrDefaultExample2 {

   public static void main(String[] args) {

       String text = "Ravi is a student. Ravi likes to code. Mehak is also a student.";

      

       // Create a HashMap to store word counts

       HashMap<String, Integer> wordCount = new HashMap<>();       

       // Split the text into words

       String[] words = text.split("\\s+");       

       // Count the occurrences of each word

       for (String word : words) {

           wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);

       }       

       // Print the word counts

       for (String word : wordCount.keySet()) {

           System.out.println(word + ": " + wordCount.get(word));

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

a: 2
student.: 2
Ravi: 2
code.: 1
Mehak: 1
is: 2
also: 1
to: 1
likes: 1


In this example, we have a string variable `text` that contains a sentence. We want to count the occurrences of each word in the text.

We create a HashMap called `wordCount` to store the word counts. We split the text into individual words using the `split()` method.

Then, we iterate over each word using a for-each loop. For each word, we use the `getOrDefault()` method to retrieve the current count of the word from the HashMap. If the word is not present, the method returns the default value of 0. We increment the count by 1 and put the updated count back into the HashMap using the `put()` method.

Finally, we iterate over the keys of the HashMap using the `keySet()` method and print each word along with its count.

Frequently Asked Questions

What happens if the key passed to the getOrDefault() method is null?

If the key passed to the getOrDefault() method is null, it will return the default value specified as the second parameter unless the HashMap contains a mapping for the null key.

Can the default value passed to the getOrDefault() method be null?

Yes, the default value passed to the getOrDefault() method can be null. If the specified key is not found and the default value is null, the method will return null.

Is the getOrDefault() method thread-safe?

The getOrDefault() method itself is not thread-safe. However, the thread safety of the HashMap depends on how it is used and whether it is accessed concurrently by multiple threads. If multiple threads access and modify the HashMap simultaneously, you need to ensure proper synchronization to maintain thread safety.

Conclusion

In this article, we explained the Java HashMap getOrDefault() method. We discussed its syntax, parameters, and return value. We also saw examples that show how to use the getOrDefault() method to retrieve values from a HashMap and provide default values when keys are not found. The getOrDefault() method is an easy way to handle cases where a key might not exist in the HashMap, which helps us avoid the need for explicit null checks.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass