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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Building and Deploying Microservices With Spring Boot and Docker
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • What Is React? A Complete Guide

Trending

  • Building and Deploying Microservices With Spring Boot and Docker
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • What Is React? A Complete Guide
  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?

Atul Verma user avatar by
Atul Verma
·
Nov. 01, 19 · Presentation
Like (6)
Save
Tweet
Share
60.44K 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.

Trending

  • Building and Deploying Microservices With Spring Boot and Docker
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • What Is React? A Complete Guide

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: