Lesson contents

Java — Counting values with List and Map

A Java Map can associate a string key with an integer count. Map.merge stores the first count for a missing key and combines later counts for the same key.

A simple example

Look up one count

  1. Start with Key A has value 2
  2. Do this Look up A
  3. Result 2
The key identifies which stored value to read.
Main.java
import java.util.Map;
class Main {
    public static void main(String[] args) throws Exception {
        var counts = Map.of("A", 2);
        System.out.println(counts.get("A"));
    }
}
Output
2
Advertisements

Count labels without relying on storage order

The Map interface describes the operations and HashMap supplies the storage. merge inserts 1 for the first occurrence and calls Integer::sum for an existing key. Use a List for predictable display order.

Scan order: Red, blue, red. Red team: 2 wristbands. Blue team: 1 wristband.
Count team wristbands

A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.

Run the example

Java 17 or later. Run these commands from the directory containing the example.

java Main.java
Main.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Main {
    public static void main(String[] args) {
        Map<String, Integer> counts = new HashMap<>();
        for (String color : List.of("red", "blue", "red")) {
            counts.merge(color, 1, Integer::sum);
        }
        for (String color : List.of("red", "blue")) {
            System.out.println(color + " " + counts.get(color));
        }
    }
}
Output
red 2
blue 1

The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.

Try it yourself

Insert another blue before the last red. What changes?

Check your answer

Both keys now have a count of two. The requested display order stays red, then blue.

Java language tutorials

Related tags

  • Java
  • collections
  • frequency counts
  • lookup