Learn Java · lesson 31 of 61 · about 8 minutes
HashMap
Price snacks from a menu: look values up by key with HashMap, and use TreeMap when you need sorted keys.
What you'll learn
- Put and get key-value pairs
- Use getOrDefault and containsKey
- Choose TreeMap for sorted output
The snack bar's menu
The snack bar sells popcorn, nachos, soda and candy, each with a price in cents. Two arrays, one of names and one of prices, would have to be searched side by side to price an order. A map pairs each snack (the key) with its price (the value), so menu.get("nachos") finds the price straight away, and containsKey checks first whether the snack is sold at all.
Look things up by key
HashMap<String, Integer> prices = new HashMap<>();
put(k, v)adds or replacesget(k)reads (null if missing)getOrDefault(k, d)reads, or gives d if missingcontainsKey(k)checks
A HashMap doesn't keep keys in any particular order. TreeMap works the same way but keeps keys sorted.
A price list
import java.util.HashMap;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> prices = new HashMap<>();
prices.put("tea", 2);
prices.put("cake", 3);
prices.put("tea", 3);
System.out.println(prices.get("tea") + " " + prices.getOrDefault("soup", 0) + " " + prices.containsKey("cake"));
TreeMap<String, Integer> sorted = new TreeMap<>(prices);
sorted.put("juice", 2);
System.out.println(sorted);
}
}Output
3 0 true
{cake=3, juice=2, tea=3}Declare it as a Map
Map<String, Integer> menu = new HashMap<>(); names the variable by what it does (a Map, from java.util.Map) and picks the kind of map on the right. Code that only uses put, get and containsKey doesn't care which map it is, so switching to a TreeMap later means changing one word.
Tip
get returns null for a missing key, and doing arithmetic with that null throws a NullPointerException. Check containsKey first, or use getOrDefault.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.