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
- Start with An optional containing 0
- Do this Read it using a fallback of 7
- Result 0
Apply it to a real problem
- Start with A free sample and an unknown item
- Do this Look up each price
- Result 0 cents or price unavailable
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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);
}
}
}
0 cents price unavailable