LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 12

compute returning null removes the entry Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links