Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Reverse Polish Notation (Java -Lambdas)
class Solution {
private static final Map<String, BiFunction<Integer, Integer, Integer>> OPERATIONS = new HashMap<>();
// Ensure this only gets done once for ALL test cases.
static {
OPERATIONS.put("+", (a, b) -> a + b);
OPERATIONS.put("-", (a, b) -> a - b);
OPERATIONS.put("*", (a, b) -> a * b);
OPERATIONS.put("/", (a, b) -> a / b);
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (!OPERATIONS.containsKey(token)) {
int number2 = stack.pop();
int number1 = stack.pop();
BiFunction<Integer, Integer, Integer> operation;
operation = OPERATIONS.get(token);
int result = operation.apply(number1, number2);
return stack.pop();

This comment has been minimized.

Copy link

@nityanandrai10 nityanandrai10 commented May 25, 2021


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment