Lambda Expressions in Java: From Syntax to Streams with Runnable Examples
Learn Java lambdas from an anonymous class onward, then trace target types, stream operations, captured variables and common compiler failures with exact outputs.
KnowledgeGate Team
Exam prep & CS education

value -> value * 3 becomes meaningful when Java supplies an input type, a return type and a functional-interface contract. Start with the anonymous-class equivalent, then trace syntax, target typing, captured variables, compiler failures and a stream pipeline with predicted output. The Coding & DSA category keeps the wider Java and problem-solving route in one place.
What is a lambda expression in Java?
A lambda provides the implementation of a functional interface's single function method. It is not an untyped standalone function. An assignment, method argument or cast supplies its target type under Oracle's Java Language Specification, section 15.27.
IntUnaryOperator timesThree = new IntUnaryOperator() {
@Override
public int applyAsInt(int value) {
return value * 3;
}
};
System.out.println(timesThree.applyAsInt(7)); // 21IntUnaryOperator timesThree = value -> value * 3;
System.out.println(timesThree.applyAsInt(7)); // 21In value -> value * 3, value is the parameter, -> separates parameters from the body, and the expression supplies the returned value. The anonymous-class syntax disappears, but the int -> int contract remains. Both calls compute 7 * 3 = 21.

Target typing: assignments, arguments and casts
Choosing among Predicate, Consumer, Supplier and Function, and counting inherited abstract methods, are treated in Functional Interfaces in Java: SAM Rules, Lambdas and Runnable Examples. The narrower target-typing question is why the same lambda shape can receive a contract from an assignment, a method argument or an explicit cast.
static int applyTo41(IntUnaryOperator rule) {
return rule.applyAsInt(41);
}
IntUnaryOperator increment = n -> n + 1;
System.out.println(increment.applyAsInt(41)); // 42
System.out.println(applyTo41(n -> n * 2)); // 82
Object decrement = (IntUnaryOperator) (n -> n - 1);
var missing = n -> n + 1; // compile-time error: no target typeThe assignment gives increment an int -> int contract. The parameter of applyTo41 supplies the same contract to its argument. The cast supplies it before the lambda is stored as Object. By contrast, var cannot infer a standalone lambda type, so the final line does not compile.
Read the main lambda syntax forms
Form | Target and invocation | Exact result |
|---|---|---|
|
| Prints |
|
|
|
|
|
|
|
|
|
Zero or multiple parameters need parentheses; one inferred parameter may omit them. An expression body returns its value without return. A value-producing block needs braces and an explicit return on every path that completes normally. Parameter types may be inferred, or every parameter may be typed explicitly.
IntUnaryOperator absolute = Math::abs; is equivalent to n -> Math.abs(n) once the target type selects the integer overload. absolute.applyAsInt(-17) returns 17. A method reference changes notation, not the target-type rule.
Worked example: filter temperatures with a lambda stream pipeline

Laziness, flatMap, reduction, grouping and stream reuse are covered in Java Streams API Tutorial: Filter, Map, Reduce and Collect with Runnable Examples. The pipeline below isolates how filter and map supply target types to two lambda bodies.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class LambdaTemperatureDemo {
public static void main(String[] args) {
List<Integer> celsius = Arrays.asList(18, 27, 31, 22, 35);
List<Integer> hotFahrenheit = celsius.stream()
.filter(c -> c >= 30)
.map(c -> c * 9 / 5 + 32)
.collect(Collectors.toList());
System.out.println("Input C: " + celsius);
System.out.println("Hot F: " + hotFahrenheit);
}
}Input C: [18, 27, 31, 22, 35]
Hot F: [87, 95]filter receives a predicate and keeps 31 and 35. map receives a transforming function. With integer arithmetic, 31 * 9 / 5 + 32 = 87 and 35 * 9 / 5 + 32 = 95. Encounter order is preserved, so the result is [87, 95]. Use double arithmetic when fractional temperatures must survive instead of being truncated.
Capture local variables and understand lambda scope
String prefix = "KG-";
Function<Integer, String> ticket = id -> prefix + id;
System.out.println(ticket.apply(42)); // KG-42
// prefix = "NEW-"; // compile-time error if uncommentedThe lambda reads prefix from its enclosing method. A captured local must be final or effectively final, so reading an unchanged value is valid while reassigning it anywhere in that scope is not. The output is KG-42 because string concatenation joins the captured prefix and the input.
List<String> log = new ArrayList<>();
Consumer<String> record = item -> log.add(item);
record.accept("lambda");
System.out.println(log); // [lambda]Effective finality applies to the local reference log, not to the mutability of the referenced list. The reference is never reassigned, so adding an element compiles. Shared mutable state still needs care, especially with concurrent or parallel work. Inside a lambda, this keeps the meaning it has in the enclosing class; inside an anonymous class, this refers to the anonymous object.
Common lambda compiler errors and semantic traps
BiFunction<Integer, Integer, Integer> add =
(int a, b) -> a + b; // broken: parameter typing is mixed
BiFunction<Integer, Integer, Integer> addFixed =
(int a, int b) -> a + b;
Function<Integer, Integer> abs = n -> {
if (n >= 0) return n; // broken: no return for negative n
};
Function<Integer, Integer> absFixed = n -> {
if (n >= 0) return n;
return -n;
};All explicitly typed parameters need their own type. A block lambda that produces a value must return on every completing path. Another failure appears with overloaded methods: if both runTask(Callable<String>) and runTask(Supplier<String>) exist, runTask(() -> "done") is ambiguous. Cast the lambda to the intended interface or rename the operations so the call has one target.
One trap compiles: Comparator<Integer> bad = (a, b) -> a - b;. For Integer.MIN_VALUE and 1, subtraction overflows to 2147483647, which has the wrong sign. Use Comparator<Integer> safe = Integer::compare;. A checked exception also needs a target method that declares it or a lambda body that handles it; Files.readString(path) cannot be dropped directly into Function<Path, String> because Function.apply does not declare IOException.
How exams and interviews test lambdas, plus three exercises
For any trace, identify the target interface, infer every parameter type, evaluate the body with the supplied inputs, and then check return paths, capture and overload constraints. These three checks separate syntax recognition from output prediction:
Declare
IntBinaryOperator cappedAdd = (a, b) -> Math.min(100, a + b);.cappedAdd.applyAsInt(64, 49)returns100because64 + 49 = 113and the cap is 100.Declare
Predicate<String> javaFile = name -> name.endsWith(".java");.javaFile.test("App.java")is true, whilejavaFile.test("README.md")is false.Declare
IntUnaryOperator halfThenAddOne = n -> n / 2 + 1;.halfThenAddOne.applyAsInt(9)returns5because integer division gives9 / 2 = 4before adding 1.
Interview follow-ups often change one condition rather than the whole expression. If javaFile must ignore case, normalise the name deliberately before endsWith. If the arithmetic must retain halves, change the target interface and numeric types instead of expecting integer division to produce a decimal.
Lambda expressions in Java: the short version and next step
A lambda implements one functional-interface method and needs a target type.
Expression and block bodies follow different return rules.
Captured local variables cannot be reassigned.
Stream operations provide target types to their lambda arguments.
Predicted output must include Java integer, overload and exception rules.
Change the stream threshold from 30 to 25 before running it. The retained Celsius values become [27, 31, 35], and integer conversion produces [80, 87, 95]. That prediction checks filtering, mapping and encounter order in one small edit.
Continue with Java: Concepts, MCQs and Coding Questions for language practice, then use DSA using Java for data-structure and interview problems.
Keep learning
Lambda Expressions in C++: Syntax, Captures and Worked Examples
Learn how C++ lambdas store captured state, accept parameters and work with STL algorithms. Follow each example from creation to exact output.
Java Streams API Tutorial: Filter, Map, Reduce and Collect with Runnable Examples
Learn Java streams from the source-to-terminal mental model, then trace operations, reductions and collectors through runnable examples and practice tasks.
Serialization in Java: Object Streams, transient, serialVersionUID and Runnable Examples
Write and restore a complete Student object, trace every retained field, and learn how Java handles transient, static, shared and evolving state.
JSX in React: Syntax, Expressions, Lists and a Runnable Worked Example
Learn the mental model behind JSX, then build and trace a five-topic React component. The examples cover syntax rules, calculations, props, events, conditional output, list keys and common repairs.





