Distinguish a zero price from a missing price in Java

Optional.ofNullable preserves a recorded zero and represents a missing map entry as empty. Map the value to a display string before providing the fallback.

A simple example

Read it using a fallback of 7

  1. Start with An optional containing 0
  2. Do this Read it using a fallback of 7
  3. Result 0
A present zero uses the stored value.

Apply it to a real problem

  1. Start with A free sample and an unknown item
  2. Do this Look up each price
  3. Result 0 cents or price unavailable
A known zero price and a missing price need different labels.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Map<String, Integer> prices = Map.of("sample", 0);
        for (String key : List.of("sample", "unknown")) {
            String text = Optional.ofNullable(prices.get(key))
                    .map(cents -> cents + " cents").orElse("price unavailable");
            System.out.println(text);
        }
    }
}
Output
0 cents
price unavailable

Official Java documentation