HashMap: keys and values
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A map stores pairs: a key and its value. You give the key, and the map gives back the value, just as a product name gives its price in an online store. HashMap is the map Java programmers use most.
What is a map?
A map is a collection that stores pairs: a key and its value. You give a key and the map gives back its value. Each key appears once, so a map never holds two entries for the same key.
An online store looks up a product's price by its name. A map does exactly that. Below, a HashMap (the map class used most) stores three prices with put, then reads them with get, containsKey and containsValue.
Example 1 · A store price list
import java.util.HashMap;import java.util.Map;
public class StoreDemo { public static void main(String[] args) { Map<String, Integer> price = new HashMap<>(); price.put("Pen", 10); price.put("Eraser", 15); price.put("Notebook", 40);
System.out.println("Products in the catalog: " + price.size()); System.out.println("Notebook costs Rs. " + price.get("Notebook")); System.out.println("Pen in the catalog? " + price.containsKey("Pen")); System.out.println("Ruler in the catalog? " + price.containsKey("Ruler")); System.out.println("Anything for Rs. 15? " + price.containsValue(15)); }}Products in the catalog: 3 Notebook costs Rs. 40 Pen in the catalog? true Ruler in the catalog? false Anything for Rs. 15? true
What this code does
- Each
putstores one entry: the item name is the key, the price is the value. get("Notebook")finds the price from the key, without any loop.containsKeychecks keys;containsValuechecks values.
A map has two type parameters: Map<K, V>, where K is the key type and V is the value type. We write Map<String, Integer> price = new HashMap<>(); and program to the Map interface, just as with List and Set.
Map<String, Integer>, never Map<String, int>. Autoboxing turns 85 into an Integer for you.Key, value and entry
An entry is one key together with its value, such as "Pen" and 10. The key is what you search by; the value is the data stored for it. Keys are unique, but two keys may have the same value.
In the picture, the left column holds the keys, the right column holds the values, and each pair is one entry. Eraser and Marker both have the value 15, which is allowed, but Pen can be a key only once.
Maps are everywhere in a real store: a product name gives its price, an order number gives its status, a customer id gives a customer, and a coupon code gives its discount.
The main methods
put adds or updates an entry, get reads a value and remove deletes an entry. Below, one marks map shows what each call returns, and how put treats a key that is already there.
Example 2 · put replaces the old value and returns it
import java.util.HashMap;import java.util.Map;
public class MarksUpdateDemo { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<>();
System.out.println("First put returns: " + marks.put("Riya", 72)); marks.put("Arjun", 85);
Integer old = marks.put("Riya", 78); System.out.println("Riya's old marks: " + old); System.out.println("Riya's new marks: " + marks.get("Riya")); System.out.println("Students: " + marks.size());
Integer removed = marks.remove("Arjun"); System.out.println("Removed Arjun, who had " + removed); System.out.println("Remove Arjun again: " + marks.remove("Arjun")); System.out.println(marks + ", empty? " + marks.isEmpty()); }}First put returns: null
Riya's old marks: 72
Riya's new marks: 78
Students: 2
Removed Arjun, who had 85
Remove Arjun again: null
{Riya=78}, empty? falseWhat this code does
- The first
putfor a key returnsnull. The secondputforRiyareplaces 72 with 78 and returns 72. - The size stays 2: a key appears only once, so a second
putupdates instead of adding. removereturns the removed value, ornullwhen the key is not there.
put(key, value) replaces the old value and returns it; for a new key it returns null. That is how a map keeps keys unique. remove(key) deletes the entry and returns its value. Small helpers: containsKey, containsValue, size, isEmpty, putIfAbsent (add only when the key is new) and clear.
Predict the output
What do put, putIfAbsent and remove return?
Read each program and pick what it prints.
Round 1 of 3
A new key, then the same key again.
When the key is missing
Unboxing means Java turns a wrapper object like Integer into its plain value like int. If the object is null, unboxing fails with a NullPointerException, which is what int x = map.get(missingKey) does.
get returns null for a key that is not in the map. Assigning that null to an int crashes the program. Below, you first see the crash, then the safe version with containsKey and getOrDefault.
Example 3 · Mistake: unboxing a missing value
import java.util.HashMap;import java.util.Map;
public class MissingKeyDemo { public static void main(String[] args) { Map<String, Integer> fees = new HashMap<>(); fees.put("Riya", 45000); fees.put("Arjun", 52000);
int riyaFee = fees.get("Riya"); System.out.println("Riya pays Rs. " + riyaFee);
int kabirFee = fees.get("Kabir"); System.out.println("Kabir pays Rs. " + kabirFee); }}Riya pays Rs. 45000 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null at MissingKeyDemo.main(MissingKeyDemo.java:13)
What this code does
fees.get("Kabir")returnsnull, because there is no such key.- Java tries to turn that
nullinto anint(unboxing) and throws aNullPointerExceptionon line 13. - The message even says it: the return value of
Map.getis null.
Example 4 · The fix: containsKey and getOrDefault
import java.util.HashMap;import java.util.Map;
public class WalletDemo { public static void main(String[] args) { Map<String, Integer> wallet = new HashMap<>(); wallet.put("riya@okaxis", 1200); wallet.put("arjun@ybl", 300);
String[] payers = {"riya@okaxis", "kabir@paytm", "arjun@ybl"}; int amount = 500;
for (String upiId : payers) { if (!wallet.containsKey(upiId)) { System.out.println(upiId + ": no such UPI ID"); continue; } int balance = wallet.get(upiId); if (balance >= amount) { wallet.put(upiId, balance - amount); System.out.println(upiId + ": paid Rs. " + amount + ", balance Rs. " + wallet.get(upiId)); } else { System.out.println(upiId + ": not enough balance (Rs. " + balance + ")"); } }
System.out.println("Kabir's balance: Rs. " + wallet.getOrDefault("kabir@paytm", 0)); }}riya@okaxis: paid Rs. 500, balance Rs. 700 kabir@paytm: no such UPI ID arjun@ybl: not enough balance (Rs. 300) Kabir's balance: Rs. 0
What this code does
containsKeyruns beforeget, sogetis only called for keys that exist. Nonullis ever unboxed.- To change a value,
putthe new value for the same key. getOrDefault("kabir@paytm", 0)returns 0 instead ofnullfor a missing key.
There are two safe ways. getOrDefault(key, 0) returns 0 (or any default you choose) when the key is missing. Or check containsKey(key) first and handle the missing case yourself, for example with a message.
Find the bug
Find the missing-key bug
Each snippet can crash or fail. Tap the wrong line, then check the fix.
Print a customer's loyalty points.
Round 1 of 3HashMap allows one null key and null values, so get returning null can mean "missing" or "stored as null". containsKey tells the two apart.HashMap and the printing order
HashMap is the most used Map class. It finds a value from its key very fast, in constant time on average, but it does not promise any order of its entries. It allows one null key and many null values.
System.out.println(map) prints {key=value, key=value}. Below, four students and their houses are put in one order and printed in another: the printed order is not the order of the put calls.
Example 5 · Printing a map: values may repeat, order is not promised
import java.util.HashMap;import java.util.Map;
public class HouseDemo { public static void main(String[] args) { Map<String, String> house = new HashMap<>(); house.put("Riya", "Red"); house.put("Arjun", "Blue"); house.put("Meera", "Red"); house.put("Kabir", "Green"); house.put("Riya", "Yellow");
System.out.println(house); System.out.println("Students: " + house.size()); }}{Meera=Red, Riya=Yellow, Arjun=Blue, Kabir=Green}
Students: 4What this code does
Meeraand the oldRiyaentry share the valueRed: values may repeat. The keyRiyaappears once, with its latest value.- The printed order is not the order of the
putcalls. It comes from the keys' hash codes and is not guaranteed.
HashMap places each key by its hash code (a number made from the key), and the printed order comes from that. Java does not promise any order, and the order can change when the map grows, so never write code that depends on it. LinkedHashMap and TreeMap (opens in a new tab) keep insertion order or sorted order.
Example 6 · Full example: PNR status lookup
import java.util.HashMap;import java.util.Map;
public class PnrDemo { public static void main(String[] args) { Map<String, String> status = new HashMap<>(); status.put("4521837690", "Confirmed, B2 34"); status.put("8812004517", "Waiting list 12"); status.put("2209761143", "RAC 5");
// A waiting ticket gets confirmed String before = status.put("8812004517", "Confirmed, S4 61"); System.out.println("8812004517 was: " + before);
// A new booking must never overwrite an old one status.putIfAbsent("4521837690", "Waiting list 40"); status.putIfAbsent("6100293854", "Confirmed, A1 7");
String[] queries = {"4521837690", "8812004517", "6100293854", "1111111111"}; for (String pnr : queries) { System.out.println(pnr + " -> " + status.getOrDefault(pnr, "PNR not found")); } System.out.println("Bookings stored: " + status.size()); }}8812004517 was: Waiting list 12 4521837690 -> Confirmed, B2 34 8812004517 -> Confirmed, S4 61 6100293854 -> Confirmed, A1 7 1111111111 -> PNR not found Bookings stored: 4
What this code does
puton an existing PNR updates the status and hands back the old one.putIfAbsentignored the first call, because4521837690already had a status. It added6100293854, which was new.- One
getOrDefaultcall gives either the status or a friendly message.
Next step
Check your understanding
12 quick questions