Library contents

Java Map.getOrDefault

Use getOrDefault to return an agreed fallback when a key is absent. A stock screen can display zero for a product that has no entry.

A simple example

Map.getOrDefault

  1. Start with Map with A = 2
  2. Do this Read missing B with fallback 0
  3. Result 0
The lookup supplies zero because B has no stored value.

Syntax

Java syntax
stock.getOrDefault(product, 0)
Run these examples in Java

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

java Main.java

Check two shelves

One shelf has a recorded quantity of tea, while cocoa has no stock entry. The clerk needs a default for the missing item without adding an entry to the stock ledger.

First output line6
Main.java
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        var stock = Map.of("tea", 6);
        System.out.println(stock.getOrDefault("tea", 0));
        System.out.println(stock.getOrDefault("cocoa", 0));
        System.out.println(stock.containsKey("cocoa"));
    }
}
Output
6
0
false

Tea has a recorded quantity. Cocoa uses the fallback, and the last line shows that looking it up did not create an entry.

Advertisements

Show a balance for an item never received

A kiosk receives its first delivery of pencils but has yet to receive any rulers. Its stock display should show zero for rulers while keeping the ledger limited to products actually received.

Result0 on hand, 1 product
Main.java
import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) throws Exception {
        var stock = new HashMap<>(Map.of("Pencil", 12));
        System.out.println(stock.getOrDefault("Ruler", 0) + " on hand, " + stock.size() + " product");
    }
}
Output
0 on hand, 1 product

The fallback supplies a display value without adding Ruler to the map.

Look up a borrowed tripod

The equipment desk has a two-day loan period for a camera, but no special period for a tripod. The system uses the recorded value when present and the displayed fallback otherwise. Which value reaches the screen?

Giventripod missing · default 7 days
Worked result7

What to watch for

Reading a default does not insert the missing key. A key explicitly mapped to null has different behavior from an absent key.

Documentation for Map.getOrDefault