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();
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:
[[email protected]]# java UnderstandingHashmapGetOrDefault
Value of currency 12 is Unknown
Value of currency 100 is Hundred Dollars
*/