Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Set and Map

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.

The shortcut

Listen to the question. "Which different…?" or "Have we seen…?" → Set. "How many per…?", "What is the … of…?" → Map, with the thing after "per" or "of" as the key. Then ask whether order matters, and pick Hash, LinkedHash or Tree.

Cups sold per drink, sorted by nameStep 1 of 4
  1. Spot the word

    "per drink": the drink name is the key and the count is the value, so a Map.

Drills

Answer fast — trust the rule.

quick drill

A HashSet<String> receives "Latte", "Tea", "Latte", "Mocha", "Tea". What is its size?

quick drill

After put("Latte", 300) and then put("Latte", 320), what is get("Latte")?

quick drill

What does priceCents.get("Chai") return when "Chai" was never added?

quick drill

A report must list drinks alphabetically with their counts. Which type fits best?

Remember

  • A Set keeps each value once; a Map finds a value by its key.
  • "Which different" → Set; "how many per" → Map keyed by the thing after "per".
  • Traps: expecting HashSet or HashMap to keep order, and get returning null for a missing key.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainClosing-time questions

From a list of every drink sold today, Brew Bar wants (1) the set of distinct customers who bought something and (2) the total cups sold for each drink, printed in the order each drink was first sold. Choose a collection type for each, explain the choice, and describe how you would fill the second one.