DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Understanding k-NN Search in Elasticsearch
  • Evaluating Similariy Digests: A Study of TLSH, ssdeep, and sdhash Against Common File Modifications
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • How to Implement Linked Lists in Go

Trending

  • Server-Driven UI: Agile Interfaces Without App Releases
  • Exploring Data Redaction Enhancements in Oracle Database 23ai
  • Run Scalable Python Workloads With Modal
  • Rust: The Must-Adopt Language for Modern Software Development
  1. DZone
  2. Data Engineering
  3. Data
  4. HashMap: get() Vs. getOrDefault()

HashMap: get() Vs. getOrDefault()

Want to learn more about retrieving values in HashMap?

By 
Atul Verma user avatar
Atul Verma
·
Nov. 01, 19 · Presentation
Likes (6)
Comment
Save
Tweet
Share
64.3K Views

Join the DZone community and get the full member experience.

Join For Free

HashMap

When a developer is working on a module, they always come across some form of data structure, like set, queue, list, etc. Data structures are used for storing Java objects in a certain fashion so that they are easy to retrieve when needed.

You may also like: How HashMap Works in Java

The right data structure makes functionality more efficient and effective — otherwise, it would be a nightmare as the implementation expands. You can start with a Map of one of the data structures where objects are stored in the key-value format. And with the help of key, we can easily retrieve the value in time complexity of O(1).

How Can We Retrieve a Value in HashMap?

Using the get() Method of HashMap

In HashMap, get(Object key) method is used to retrieve the value of a key. So, if we have a key then we easily fetch the value from the hashmap using the get method. Please follow the below snapshot for same:

Map<String, Integer> products = new HashMap<>();
products.put("1234", 1000);
products.put("4567", 2000);

// get the price of productId 4567.
Integer price = products.get("4567");

// print price of product.
System.out.println("Price of product 4567 is : " + price);


In the above example, we have a product map with the productId and price. We are trying to fetch the price of productId:4567, so 2000 will return. But what happens if we pass a productId that doesn't exist in the map in the above example? We will get the null value; this is not good. So, instead of returning the null value, there should be some default value of the price. In the screenshot below, we can learn how to set the default value for a key that doesn't exist:

Map<String, Integer> products = new HashMap<>();
products.put("1234", 1000);
products.put("4567", 2000);

// get price of productId 7890.
Integer price = products.get("7890");

// check if price is null, then set default value to 500.
if(null == price){
price = 500;
}

// print the price of product.
System.out.println("Price of product 7890 is : " + price);


In the above example, we set the default price to 500 if the price cannot be found for the product. Through this, we can easily avoid the null value if the productId cannot be found with a default value. But for this, we have to put an additional null check for each value in the product map.

So, do we have any other way to set the default value for non-existing keys?

In fact, we do.

Using the getOrDefault() Method in HashMap

Let see how can we override the above approach without adding a null check. One new out-of-the-box method of Map that was introduced in Java8 will help here. We will provide a default value in that method itself, so if key doesn't exist, then the default value will be returned instead of null. Check out the solution below:

Map<String, Integer> products = new HashMap<>();
products.put("1234", 1000);
products.put("4567", 2000);

// get price of productId 7890.
Integer price = products.getOrDefault("7890", "500");

// no longer need, as above method do the same job.
//if(null == price){
//price = 500;
//}

// print the price of product.
System.out.println("Price of product 7890 is : " + price);


In the above example, we can see how the getOrDefault() method works. When trying to fetch the price of productId:7890, which doesn't exist in the product map, we get the default price of 500. So for any unfound key, we have a default value instead of null.

Conclusion

In the examples above, we went through two methodologies to fetch a value from hashmap. With the first one, we will get a null value. With later one, we can always retrieve the value — whether the actual or default value. But it doesn't mean that we should not use the get() method of HashMap. For example, in some use cases, we need to check the non-existence of the key and perform operations based on the absence. So, in those cases, getOfDefault will not be useful. So it totally depends on your use case, and based on that, we can decide when to use which one.

Hope this helps! Happy HashMaping!

Further Reading

How HashMap Works in Java

How to Use Java HashMap Effectively

Data structure

Opinions expressed by DZone contributors are their own.

Related

  • Understanding k-NN Search in Elasticsearch
  • Evaluating Similariy Digests: A Study of TLSH, ssdeep, and sdhash Against Common File Modifications
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • How to Implement Linked Lists in Go

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: