Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Maps and sorting

By the end of this chapter, you'll be able to

  • Associate keys with values with HashMap and TreeMap
  • Read a value safely with getOrDefault and count with merge
  • Go through a map with entrySet
  • Sort a list in natural order or by a criterion

HashMap and TreeMap

void main() {
    Map<String, Integer> stock = new TreeMap<>();
    stock.put("rice", 40);
    stock.put("oil", 12);
    stock.put("sugar", 25);
    stock.put("rice", 35);                         // same key: the value is replaced

    IO.println(stock);
    IO.println("Rice: " + stock.get("rice"));
    IO.println("Flour: " + stock.getOrDefault("flour", 0));
    IO.println("Any sugar? " + stock.containsKey("sugar"));

    for (Map.Entry<String, Integer> e : stock.entrySet()) {
        IO.println("- " + e.getKey() + ": " + e.getValue());
    }
}
{oil=12, rice=35, sugar=25}
Rice: 35
Flour: 0
Any sugar? true
- oil: 12
- rice: 35
- sugar: 25
  • Map<String, Integer>: String keys, Integer values. Each key is unique: put on an existing key replaces its value.
  • get(key) returns the value, or null if the key is missing. getOrDefault(key, fallback) returns a fallback value instead.
  • entrySet() gives the pairs; each pair (Map.Entry) has a key (getKey()) and a value (getValue()).
  • TreeMap keeps the keys sorted. HashMap, which is faster, guarantees no order at all when going through it. You declare the variable with the general type Map and choose the implementation at the new.

Counting with merge

Counting occurrences is such a frequent need that maps have a dedicated method: merge(key, 1, Integer::sum) adds 1 to the key's value, or creates it with 1 if it doesn't exist yet.

A map displays directly in the form {key=value, …}.

Step 6 of 6
Text description of the animation
  1. We count the votes for a team colour.
  2. The map is empty.
  3. "green" doesn't exist: merge creates the key with the value 1.
  4. Same for "blue". The TreeMap keeps its keys in alphabetical order.
  5. "green" exists: merge adds the old value and 1, with Integer::sum.
  6. A map displays directly in the form {key=value, …}.

Integer::sum is a method reference: we pass the sum method of the Integer class (which adds two integers) so that merge uses it.

Sorting a list

void main() {
    var cities = new ArrayList<>(List.of("Lagos", "Oslo", "Bogotá", "Hanoi", "Accra"));
    Collections.sort(cities);
    IO.println(cities);

    cities.sort(Comparator.comparing(String::length));
    IO.println(cities);

    cities.sort(Comparator.reverseOrder());
    IO.println(cities);
}
[Accra, Bogotá, Hanoi, Lagos, Oslo]
[Oslo, Accra, Hanoi, Lagos, Bogotá]
[Oslo, Lagos, Hanoi, Bogotá, Accra]
  • Collections.sort(list) sorts in natural order: alphabetical for texts, increasing for numbers.
  • Comparator.comparing(String::length) sorts by a criterion: here the length. Java's sort is stable: for equal lengths, items keep their previous order (Accra, Hanoi, Lagos).
  • Comparator.reverseOrder() sorts in reverse order.
  • List.of(...) creates an unmodifiable list: we copy it into an ArrayList so we can sort it.

Your turn

Worked exercise

Worked exercise: the best seller

Here are the day's sales, one per line: "Awa:120", "Liam:80", "Awa:45", "Noor:150", "Liam:95". Compute the total per seller in a TreeMap, display it, then display the best seller: {Awa=165, Liam=175, Noor=150} and Best: Liam (175).

Hint 1
line.split(":") cuts the text into an array of two pieces: the name and the amount (to convert with Integer.parseInt).
Hint 2
totals.merge(name, amount, Integer::sum) adds up the amounts. For the best one, go through entrySet() keeping the pair with the highest value.
Show the solution and common mistakes
void main() {
    var sales = List.of("Awa:120", "Liam:80", "Awa:45", "Noor:150", "Liam:95");
    Map<String, Integer> totals = new TreeMap<>();
    for (String line : sales) {
        String[] parts = line.split(":");
        totals.merge(parts[0], Integer.parseInt(parts[1]), Integer::sum);
    }
    IO.println(totals);

    String best = null;
    int max = 0;
    for (Map.Entry<String, Integer> e : totals.entrySet()) {
        if (best == null || e.getValue() > max) {
            best = e.getKey();
            max = e.getValue();
        }
    }
    IO.println("Best: " + best + " (" + max + ")");
}
{Awa=165, Liam=175, Noor=150}
Best: Liam (175)

Common mistakes:

  • Using put instead of merge: Awa's second sale would replace the first instead of adding to it.
  • Comparing two Integers with ==: for values above 127, two equal Integer objects may be distinct objects. Here, e.getValue() > max compares an Integer with an int, which is safe.

Summary

  1. 1A Map associates unique keys with values: put, get, getOrDefault, containsKey.
  2. 2TreeMap keeps its keys sorted; HashMap is faster but with no guaranteed order.
  3. 3merge(key, 1, Integer::sum) counts occurrences in one line.
  4. 4Collections.sort sorts in natural order; Comparator.comparing sorts by a criterion.
  5. 5get returns null for a missing key: prefer getOrDefault.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.