Library contents

Java Map.entrySet, Map.keySet and Map.values

Use entrySet to visit keys and values together, keySet for just the keys, and values for the mapped values.

A simple example

Map.entrySet, Map.keySet and Map.values

  1. Start with B = 2, A = 1
  2. Do this Visit entries in key order
  3. Result A = 1, then B = 2
Ordering the keys before visiting them gives a predictable sequence.

Syntax

Java syntax
for (var entry : sales.entrySet())
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Print shelf totals in aisle order

A stockroom supervisor sends a short inventory message each evening. Both the aisle name and its count belong on each line, and the message must follow aisle order every time.

From the programlines.add(entry.getKey() + "=" + entry.getValue())
ResultA=4, B=2
Main.java
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

class Main {
    public static void main(String[] args) throws Exception {
        var stock = new TreeMap<>(Map.of("B", 2, "A", 4));
        var lines = new ArrayList<String>();
        for (var entry : stock.entrySet()) {
            lines.add(entry.getKey() + "=" + entry.getValue());
        }
        System.out.println(String.join(", ", lines));
    }
}
Output
A=4, B=2

TreeMap visits the aisle keys in sorted order. Each entry supplies its own count.

Advertisements

Count outlets and sum their deliveries

Two outlets report the number of crates they received today. The coordinator counts the distinct outlet keys and adds all crate counts, including equal counts from different outlets.

From the programint total = 0
Result2 outlets, 6 crates
Main.java
import java.util.Map;

class Main {
    public static void main(String[] args) throws Exception {
        var deliveries = Map.of("East", 3, "West", 3);
        int total = 0;
        for (int crates : deliveries.values()) total += crates;
        System.out.println(deliveries.keySet().size() + " outlets, " + total + " crates");
    }
}
Output
2 outlets, 6 crates

There are two keys and two values of three. The values view retains both counts.

Print stock by aisle

A delivery entered the second aisle before the first. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?

GivenB → 3 · A → 2
Worked resultA 2 · B 3

What to watch for

Map views are backed by the map. HashMap has no guaranteed iteration order, so sort or use a suitable ordered map when order matters.

Documentation for Map.entrySet, Map.keySet and Map.values