AI Hints
Home›Java Tutorial›HashMap, Looping Over a Map and HashSet
Java · Lesson 85 of 120

HashMap

Keys and values.

⏱ 2 min read▶ Video at 1:48:00🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A map stores pairs. Each key leads to a value, like a word and its meaning, or a product and its price. You look things up by key, not by position.

  • Pairs of key and value
  • Look up by key
  • Not by position

A price list

A HashMap has two types, one for the keys, and one for the values. Put adds a pair. Get looks up a value by its key. Putting the same key again replaces the old value. Get gives null if a key isn't there. Get or default gives a fallback instead. Contains key checks for a key, and remove deletes a pair. Run it. Coffee costs three twenty, then three forty. Juice is null, or zero with a default. And two items are left.

Main.javajava
import java.util.HashMap;
public class Main {
    public static void main(String[] args) {
        HashMap<String, Double> prices = new HashMap<>();
        prices.put("tea", 2.50);
        prices.put("coffee", 3.20);
        prices.put("cake", 4.00);
        System.out.println("Coffee costs " + prices.get("coffee"));
        prices.put("coffee", 3.40);
        System.out.println("Now " + prices.get("coffee"));
        System.out.println("Juice: " + prices.get("juice"));
        System.out.println("Juice or 0: " + prices.getOrDefault("juice", 0.0));
        System.out.println("Has cake? " + prices.containsKey("cake"));
        prices.remove("cake");
        System.out.println(prices.size() + " items: " + prices);
    }
}
Output
Coffee costs 3.2
Now 3.4
Juice: null
Juice or 0: 0.0
Has cake? true
2 items: {tea=2.5, coffee=3.4}

Map rules

Each key appears only once. Values can repeat. A HashMap doesn't keep any order. And looking up a key is extremely fast, even with millions of pairs.

keyvalue
Keysunique
Valuescan repeat
Ordernone in HashMap
Lookupvery fast

Summary

A HashMap links keys to values. Put, get, get or default, contains key, and remove are the main methods. Next, looping over a map.

Key takeaways
  • Map<K, V>
  • put, get
  • Keys are unique
Next up: Looping Over a Map — keys, values, entries