Skip to the workspace
Pebellslearn by building
Collections  ›  Lesson

Set and Map

Map 15 minA Set stores each distinct value once, and a Map stores unique keys that each point to one value, with Hash, LinkedHash and Tree versions giving no order, insertion order or sorted order.

java / Set and Map

Explore each scene at your own pace.

01 · The rule

The rule

Set and Map

A Set stores each distinct value once, and a Map stores unique keys that each point to one value, with Hash, LinkedHash and Tree versions giving no order, insertion order or sorted order.

Distinguish membership from key-based lookup and inspect duplicate handling.

At closing time the manager asks two questions: "Which different drinks did we sell today?" and "How many of each?" A list of every sale holds the answer, but digging it out is slow and fiddly. A Set answers the first question by design, and a Map answers the second.

The rule

A Set keeps each value once; a Map finds a value by its key.

A Set is a collection with no duplicates. Adding something already present does nothing, and add returns false to tell you so:

Set<String> soldToday = new HashSet<>();
soldToday.add("Latte");
soldToday.add("Mocha");
soldToday.add("Latte");                  // ignored, returns false
System.out.println(soldToday.size());    // 2
System.out.println(soldToday.contains("Mocha"));  // true

contains on a HashSet is very fast, however big the set grows, which makes sets ideal for "have we seen this?" checks.

A Map stores key → value pairs. Keys are unique; each one points to exactly one value:

Map<String, Integer> priceCents = new HashMap<>();
priceCents.put("Latte", 300);
priceCents.put("Mocha", 340);
priceCents.put("Latte", 320);                     // replaces 300
System.out.println(priceCents.get("Latte"));      // 320
System.out.println(priceCents.get("Chai"));       // null: no such key
System.out.println(priceCents.getOrDefault("Chai", 0));  // 0

Counting is a classic Map job. merge adds 1 to the existing count, or starts at 1 if the key is new:

Map<String, Integer> cupsSold = new HashMap<>();
for (String drink : sales) {
    cupsSold.merge(drink, 1, Integer::sum);
}

Order depends on which implementation you choose:

Implementation Iteration order
HashSet, HashMap no promised order
LinkedHashSet, LinkedHashMap the order items were first added
TreeSet, TreeMap sorted by value or key

To walk through a map, loop over map.entrySet() and use getKey() and getValue() on each entry.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.