Programs & Examples
Lambda Expressions · Study material
A calculator driven by a map of lambdas
Each operator symbol maps to a DoubleBinaryOperator, so adding an operation is one line and no switch statement is needed.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.DoubleBinaryOperator;
public class Main {
public static void main(String[] args) {
// A table of behaviour: operator symbol → lambda (replaces a long switch)
Map<String, DoubleBinaryOperator> ops = new LinkedHashMap<>();
ops.put("+", (a, b) -> a + b);
ops.put("-", (a, b) -> a - b);
ops.put("*", (a, b) -> a * b);
ops.put("/", (a, b) -> b == 0 ? Double.NaN : a / b);
ops.put("^", Math::pow);
ops.put("max", Math::max);
String[] exprs = {"12 + 30", "7 / 2", "2 ^ 10", "5 / 0", "9 max 14", "3 % 2"};
for (String e : exprs) {
String[] p = e.split(" ");
DoubleBinaryOperator op = ops.get(p[1]);
String result = op == null ? "unknown operator " + p[1] : String.valueOf(op.applyAsDouble(Double.parseDouble(p[0]), Double.parseDouble(p[2])));
System.out.printf("%-9s = %s%n", e, result);
}
}
}
12 + 30 = 42.0 7 / 2 = 3.5 2 ^ 10 = 1024.0 5 / 0 = NaN 9 max 14 = 14.0 3 % 2 = unknown operator %
All four kinds of method reference
The method-reference example uses a static method, a bound instance method, an unbound instance method and constructors.
Composing predicates, functions and comparators
The composition example chains functions with andThen and compose, combines predicates and builds a multi-level sort.