getOrDefault returns a fallback when the key is missing, but it does not insert anything - use putIfAbsent or computeIfAbsent when you want the map changed.
Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 12, "book", 3));
System.out.println("pen = " + stock.getOrDefault("pen", 0));
System.out.println("mug = " + stock.getOrDefault("mug", 0));
System.out.println("map unchanged: " + stock);
stock.putIfAbsent("mug", 0);
stock.putIfAbsent("pen", 999);
System.out.println("after putIfAbsent: " + stock);
pen = 12
mug = 0
map unchanged: {book=3, pen=12}
after putIfAbsent: {book=3, mug=0, pen=12}
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30