Question 12
Back to Exercise
What is the output of the following Java program?
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 3, "book", 1, "bag", 5));
for (String sold : new String[]{"book", "pen", "lamp", "pen"}) {
stock.computeIfPresent(sold, (k, v) -> v > 1 ? v - 1 : null);
}
stock.compute("lamp", (k, v) -> v == null ? 10 : v + 10);
System.out.println(stock);
}
}
- A {bag=5, lamp=10, pen=1} Correct
- B {bag=5, book=0, lamp=10, pen=1}
- C {bag=5, pen=1}
- D {bag=5, book=1, lamp=10, pen=1}
Correct Answer: Option A
Returning null from the function removes the key (book sold out). computeIfPresent does nothing for the missing lamp; compute then creates it.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!