dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 17, 2020

Understanding the HashMap.getOrDefault() Method

HashMap is a class that facilitates storing data in the form a key value pair. One thing to note for HashMap is that this is not synchronized and has to be used with caution in multi-threaded environment.

We may find cases in which the key is not present and we may be trying to perform operations using the key. The following method will help us use a default value when the key in question is not available in the set of data.

import java.util.HashMap;

public class UnderstandingHashmapGetOrDefault
{
   public static void main(String args[])
   {
      UnderstandingHashmapGetOrDefault understandingHashmapGetOrDefault = new UnderstandingHashmapGetOrDefault();
      understandingHashmapGetOrDefault.proceed();
   }
   
   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

*/
M S Sridhar
 
Thanks for your registration, follow us on our social networks to keep up-to-date