Understandng HashMap.getOrDefault() method

Understandng HashMap.getOrDefault() method

HashMap is a class which which facilitates storing data in the form a key value pair. One thing to note of HashMap is that this is not synchronized and has to be used with caution in multi threaded environment. We may find cases where the key is not present and we maybe trying to perform operations using the key. Following method will help us in using a default value when the key in question is not available in the avaialble set of data.

import java.util.HashMap;

public class UnderstandingHashmapGetOrDefault
   public static void main(String args[])
      UnderstandingHashmapGetOrDefault understandingHashmapGetOrDefault = new UnderstandingHashmapGetOrDefault();
   private void proceed()
      HashMap hashMap = initHashMap();
      int currencyId = 12;
      System.out.println(“Value of currency ” + currencyId + ” is ” + hashMap.getOrDefault(currencyId, “Unknown”));
      currencyId = 100;
      System.out.println(“Value of currency ” + currencyId + ” is ” + hashMap.getOrDefault(currencyId, “Unknown”));

   private HashMap initHashMap() {
      //HashMap declaration with 2 arguments (Integer and String)
      HashMap hashMapCurrency = new HashMap();
      //Adding predefined contents to the HashMap
      hashMapCurrency.put(10, “Ten Dollars”);
      hashMapCurrency.put(20, “Twenty Dollars”);
      hashMapCurrency.put(50, “Fifty Dollars”);
      hashMapCurrency.put(100, “Hundred Dollars”);
      hashMapCurrency.put(200, “Two Hundred Dollars”);
      return hashMapCurrency;


Expected output:

[root@mypc]# java UnderstandingHashmapGetOrDefault
Value of currency 12 is Unknown
Value of currency 100 is Hundred Dollars



About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist