LearnFrenzy
Sign in Take a free test

Lambda Expressions · Predict the Output · Question 19

Command handlers stored in a map Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();
        Map<String, Consumer<Deque<Integer>>> cmds = Map.of(
            "dup", s -> s.push(s.peek()),
            "add", s -> s.push(s.pop() + s.pop()),
            "mul", s -> s.push(s.pop() * s.pop()),
            "neg", s -> s.push(-s.pop()));
        for (String tok : "3 4 add dup mul neg 2 add".split(" ")) {
            Consumer<Deque<Integer>> c = cmds.get(tok);
            if (c != null) c.accept(stack); else stack.push(Integer.parseInt(tok));
        }
        System.out.println(stack);
    }
}
  • A [-47] Correct
  • B [47]
  • C [-49, 2]
  • D [-51]
Correct Answer: Option A

3 + 4 = 7, dup → 7 7, mul → 49, neg → −49, push 2, add → −47. Each command is a Consumer lambda.

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