Passing Behavior as an Argument
So far we have passed numbers, strings and objects to a method. Sometimes we also want to pass it a choice: how to transform some text, when to accept it, what to do with the result. In Java this choice can be represented by an object implementing an interface with a single abstract method. A lambda is a concise form for providing precisely that implementation. It does not turn Java into a purely functional language, but makes it easier to treat behavior as a value usable by other operations.
Let us start with a familiar problem: a method must perform stable work, but the caller wants to change a decision. We will see how to declare the required behavior, how to pass it and how to check the result. Only when an example requires it will we give the more advanced principles a name. This way a definition does not remain suspended without a program to apply it to.
Definition – Functional interface. It is an interface with a single abstract method to implement, and is therefore also called SAM, from Single Abstract Method. It can have default or static methods without losing this property.
@FunctionalInterfaceasks the compiler to check it. The lambda receives its target type from the context: it is not an untyped piece of code that can be assigned to any variable.
Why Introduce Functions in an Object-Oriented Language
Imagine that we have a method comparing two prices. The method knows how to obtain the prices, but does not know whether the caller wants to calculate the difference, the sum or the greater value. A first solution is to pass it a numeric code, for example 1 for the sum and 2 for the difference. The method then contains a switch that grows every time a new operation appears. The number 2, read six months later, explains nothing. A second solution is to duplicate the method for every choice: this path also grows badly, because the entire part that obtains and validates the prices is repeated. The concrete need is to pass the changing behavior to the method, keeping the common work in a single place.
This problem did not begin with Java 8. The interfaces and polymorphism of Chapter 13 already solved it: we declare a contract with execute(int, int) and pass an object implementing it. Lambdas shorten the writing of the implementation when the contract has a single abstract method. The benefit is not the number of brackets saved, but the ability to see, near the call, which decision we are entrusting to the method. If the decision is complex, it still makes sense to give it a name in a class or an ordinary method.
In the complete program LambdaPathDemo.java, calculate receives three arguments: the two numbers and an Operation. The method knows neither subtraction nor addition; it calls operation.execute(a, b). The first operation is an anonymous class, the second a lambda, and the third a reference to the static method sum. The first two both print 7, and the third 13. That equal result for two different forms verifies that we have changed how we provide behavior, without changing the contract used by calculate.
@FunctionalInterface
interface Operation {
int execute(int a, int b);
default String description() {
return "operation on two integers";
}
}
static int calculate(int a, int b, Operation operation) {
return operation.execute(a, b);
}
The interface declaration makes the domain and result explicit: it receives two int values and produces an int. The description method is default: it already has a body and adds no new obligation to whoever implements the interface. This is why the interface remains functional. The annotation @FunctionalInterface does not create the property; it asks the compiler to report if a future change destroys it. If someone added int undo(int a, int b); as a second abstract method, the program would stop compiling at the point where the contract is declared, rather than only in calls scattered around the project.
From problem to solution. When a family of operations changes but whoever executes them stays the same, a functional interface represents the variable part. A lambda is one possible implementation of that contract. We verify by passing two different behaviors to the same method and observing different results on the same data; we then transfer the same idea to a name filter, a sort or a validation rule.
Before Lambdas: the Anonymous Class
An anonymous class is created in an expression with new Operation() { ... }. It has no declared name in the source, but is a concrete implementation of the interface. We have to repeat @Override, the method's complete signature and return. The form is longer because we can also declare fields and other methods in the anonymous object. It is not merely a lambda written with more words: its identity and the meaning of this are different.
Operation anonymousClass = new Operation() {
@Override
public int execute(int a, int b) {
return a - b;
}
};
Operation lambda = (a, b) -> a - b;
In the lambda line, the types of a and b are inferred from the abstract method execute. The compiler knows the target type thanks to the declaration Operation lambda. If we attempted var lambda = (a, b) -> a - b;, the target type would be missing and the compiler would not know which interface to implement. var can be used for individual parameters in a lambda when the target type is already known, for example (var a, var b) -> a - b, but does not solve the absence of the type of the entire lambda. This detail avoids a common confusion: parameter inference depends on the contract, rather than inventing it.
A function passed to calculate is a value in the practical sense that we can assign it to a variable, transmit it to a method and have a method return it. The program's method add(int increment) returns an Operation; the lambda produced uses increment in a later call. A method that receives or returns behavior is called a higher-order function. Java maintains its own type model: the value is referred to through a functional interface. Talking about “first-class functions” is useful for describing the ability to move behavior around, provided it does not make us forget the concrete type required by the compiler.
What Makes an Interface Functional
The count concerns the abstract methods to implement, rather than every line that looks like a method. A default method already has a body. A static method belongs to the interface and is not implemented by the lambda. Public methods of Object declared in an interface, such as equals(Object), do not introduce a second independent function. A hierarchy can inherit equivalent declarations of the same abstract method; the compiler checks their compatibility. It is better not to learn a superficial formula such as “only one word abstract in the file”: the criterion is that there is a single effective functional abstract contract.
Suppose we extend two interfaces, one with void send(String text) and the other with boolean check(String text). The child interface would require two behaviors and cannot be implemented by a single lambda. If instead both inherit the same signature void send(String text), the compatible declarations can represent a single functional method. It is best to let @FunctionalInterface check this: the compiler knows all the overriding rules, including return types and exceptions, better than a manual count.
An excessive number of default methods can hide an interface that has become too broad. The caution remains useful, but a well-chosen default method is not an error: Function.andThen, Predicate.and and Consumer.andThen are precisely composition methods that make the contract usable. The question to ask is whether that method belongs to the meaning of the function and whether it keeps clear what the lambda must provide. If two inherited interfaces define the same default method with conflicting bodies, the ambiguity must be resolved explicitly; the functional annotation does not decide which body to choose.
The Shape of a Lambda, Read Without Shortcuts
The arrow -> separates parameters and body. () -> "ready" receives no arguments and returns a string; text -> text.length() receives one parameter; (a, b) -> a + b receives two. Parentheses around a single inferred parameter can be omitted. A body consisting of a single expression uses the value of that expression as its result when the contract requires a value. If the body is a block between braces and the contract requires a result, a return is needed on every path that can complete normally.
BinaryOperator<Integer> shortSum = (a, b) -> a + b;
BinaryOperator<Integer> extendedSum = (a, b) -> {
int result = a + b;
return result;
};
The second form is not wrong: it may be necessary for checks or steps that deserve to remain visible. If the lambda grows to contain complex domain logic, extracting a method with a clear name helps both the reader and the debugger. Conversely, removing the braces is not possible if several statements remain. A lambda intended for Consumer<String> can call System.out.println(text) without returning a value, because the abstract method accept has a void return. The same expression cannot be assigned without checking to Function<String, String>, which promises a string as its result.
The expression x++ deserves attention: as an expression it returns the previous value of x, whereas ++x returns the next one. In a lambda UnaryOperator<Integer> increment = x -> x++;, the parameter x is a local variable of the call, so reassignment does not modify the caller's Integer object; the returned value is even the initial one. To communicate an intention to increment, x -> x + 1 is more correct and readable. Analysis of the syntax must reach observable behavior; otherwise a “compact” line teaches the wrong rule.
A lambda can throw exceptions compatible with the declaration of the abstract method. Function.apply does not declare checked exceptions, so a lambda assigned to Function cannot directly propagate, for example, an IOException without handling it. A custom interface with throws IOException instead makes that contract explicit. We should not turn every checked exception into a RuntimeException merely to enter a stream: first we decide where the error must be handled and whether a pipeline is really the right form for the problem.
The java.util.function Catalog, Starting from the Question
When looking for a functional interface, let us first ask what goes in and what comes out. Supplier<T> receives no input and supplies a T through get: it can represent a factory of values or the deferral of a calculation. Consumer<T> receives a T and performs an action with accept, without promising a result. Predicate<T> receives a T and answers true or false through test. Function<T, R> receives a T and returns an R through apply. Four forms already answer many everyday needs. In the example program, Supplier<String> label = () -> "Java" produces the text, while Predicate<String> longEnough decides whether it has at least four characters: printing true verifies that a result and a condition are not the same kind of behavior.
Box – Domain and Codomain. In mathematics, a function associates each element of the domain with a result in the codomain. In
Function<String, Integer>,Stringindicates the input type andIntegerthe output type. The Java signature alone does not express every precondition: a function callingInteger.parseIntformally acceptsString, but some strings cause an error. The teaching contract must therefore also explain the subset of valid inputs and the handling of invalid cases.
When there are two inputs, the families BiFunction<T, U, R>, BiConsumer<T, U> and BiPredicate<T, U> make the second type explicit. BinaryOperator<T> is a case of BiFunction in which both inputs and the result have the same type. UnaryOperator<T> is the case of Function<T, T>. In our program, BinaryOperator<Integer> operator = Integer::sum produces 13 when passed 10 and 3. If the numbers must remain primitive and the operation is genuinely numerical, IntBinaryOperator avoids the implicit conversion between int and Integer: its method is called applyAsInt. Choosing between two types is not reduced to the length of the declaration; it begins with semantics and, when needed, measured costs.
BiFunction<Integer, Integer, String> could take two integers and return a sentence; BinaryOperator<Integer> could not, because the result must remain Integer. These type differences help the compiler report an incorrect problem–solution association. If we try to use a Consumer to calculate a value, there is no result to assign. If we try to use a Supplier for a validation depending on a parameter, the input is missing. It is easier to remember interfaces starting from these constraints than from an alphabetical catalog of names.
Primitive variants cover common combinations: IntSupplier returns an int; IntConsumer receives it; IntPredicate evaluates it; IntFunction<R> receives an int and returns an object; ToIntFunction<T> receives an object and returns an int. Long and Double have similar families. The name indicates the direction of conversion. For example, ToIntFunction<String> length = String::length describes the path from a string to an int. Function<String, Integer> is also valid but uses the Integer wrapper; over millions of elements the distinction may matter. For a single element, the objective is first of all to have an understandable contract.
Composing Means Checking the Order
Function.andThen creates a function that applies the one on the left first and then the one passed as an argument. compose does the reverse: it first applies the function received and then the one on which the method is called. If clean removes spaces and uppercase converts letters, clean.andThen(uppercase) makes the order explicit: clean, then convert. uppercase.compose(clean) expresses the same order from another starting point. Function.identity() returns the value it receives and is mainly useful when an API requires a function but we do not want to transform the element.
To see that order is not a detail, take addPrefix = text -> "#" + text and removeFirst = text -> text.substring(1). Applying the prefix and then removing the first character brings back the starting text; reversing the steps instead removes the first original character and adds #. Composed functions do not automatically become commutative because they are pure. Before composing, we follow a concrete input through the steps and write the expected output. This is the “brick by brick” method applied to the pipeline that we will meet in Chapter 18.
Predicate.and and Predicate.or combine conditions with ordinary Boolean logic and short-circuit evaluation: for and, if the first condition is false, the second is not needed. negate reverses the result. An example: a title is valid if nonEmpty.and(shortEnough).test(title) is true. If nonEmpty excludes null with text != null, the second predicate can call length() without an error, provided the order of the two conditions remains the intended one. A name such as validTitle tells the reader the overall rule; the inner predicates explain its pieces.
Consumer.andThen executes two actions in the indicated order. Here effects matter: printing and then saving is not always equivalent to saving and then printing. If the first action throws an exception, the second is not executed. There is no “automatic purity” in functional interfaces: it is the concrete body of the lambda or the referenced method that determines whether it modifies state, performs I/O or depends on the time. This also clarifies why Supplier<Integer> random = ... is a legitimate supplier although it is not a pure function: the value can change on every call.
The Target Type Decides the Shape of the Lambda
The expression text -> !text.isBlank() takes on a precise meaning because it is assigned to Predicate<String>. From that type, the compiler derives that text is a String and that the result must be a boolean. If we assigned the same expression to an interface with an incompatible signature, compilation would fail. Parentheses around parameters can be omitted for a single parameter in a simple form; with two parameters, as in the example's BiConsumer, the list must be in parentheses. When the body contains several statements, braces are required, as is an explicit return if the function produces a value.
An overloaded method accepting two different functional interfaces can make a lambda ambiguous: the same shape might fit both. In that case we should not invent a precedence rule based on the interface name. An explicit cast, an intermediate variable with a declared type or more distinctly named APIs can clarify the choice. This is one more reason to design public signatures with those who will pass lambdas as arguments in mind.
Standard functional interfaces generally do not declare checked exceptions in their abstract method. If an operation passed to Function must read a file and can throw IOException, we cannot simply propagate that checked exception through apply. We must handle it in the body, choose a custom interface declaring throws or move reading outside the transformation. Catching the exception and replacing it with an empty value without explanation would erase a real error. The rules of Chapter 12 also apply when code is written in a lambda.
Functions That Return Functions
A function can return another function. For example, a method could receive a threshold and return a Predicate<Integer> checking whether a number exceeds it. The returned function captures the threshold value and can be used later. This is a concrete form of higher-order function: behavior is passed or returned as a typed value. There is no need to introduce a new language grammar; we use the functional interfaces, generics and lambdas already seen.
If we wrote Predicate<Integer> greaterThanTen = greaterThan(10);, the method name tells us what is constructed and the type tells us which question we can ask. A nested lambda expression might be more compact, but less readable. A name that describes the operation helps someone reading the code recognize and reuse it; reducing the character count is not enough to make the program clear.
Further reading – Currying. In theory, currying transforms a function with several arguments into a chain of functions each having one argument. In Java we can represent the idea with
Function<A, Function<B, R>>, but this form is not automatically better thanBiFunction<A, B, R>. It becomes useful only when fixing the first argument creates reusable and readable behavior. It is an optional concept for the main path.
A Readable Transformation
The complete program prepares some titles: it removes spaces at the edges, converts to uppercase, discards empty text and prints only results that are long enough. This is not a problem that necessarily requires lambdas; it is small precisely to isolate the decisions. Figure 16.1 shows the two transformations and the filter as distinct steps.
Function<String, String> clean = String::strip;
UnaryOperator<String> uppercase = String::toUpperCase;
Function<String, String> prepare = clean.andThen(uppercase);
Predicate<String> nonEmpty = text -> !text.isBlank();
Function<String, String> describes a function that receives a string and returns one. String::strip is a method reference: it says to use the strip method of the received string. It is readable here because the method name already communicates the operation. The equivalent lambda form would be text -> text.strip(). UnaryOperator<String> is a specialization of Function<String, String> for input and output of the same type. andThen builds a new function: first it executes clean, then uppercase. If we reversed the order in this case, we would obtain the same text for many inputs, but this is not a general property of functions: order must be chosen based on the meaning of the transformations.
Predicate<String> represents a question with a Boolean answer. In the code, text -> !text.isBlank() is a lambda with one parameter. The word to the left of the arrow is a local variable of the lambda; the expression on the right produces the result. We could combine predicates with and, or and negate, but a long chain of anonymous conditions would become difficult to explain. When the condition has a domain name, an ordinary method with that name can be the clearest choice.
Printing is entrusted to a BiConsumer<String, Integer>, which receives text and length and returns no value. In the program it is invoked with accept. Consumer, BiConsumer, Supplier, Predicate, Function, UnaryOperator and primitive variants are families of interfaces in java.util.function. A variant such as IntPredicate avoids boxing when the data is an int; however, there is no need to mechanically replace every type with a primitive variant. First we clarify which relationship between input and output is needed.
The program prints JAVA: 4 and 120. The title " Go " becomes GO, but does not reach the minimum length of 3. The string consisting only of spaces becomes empty and is discarded. The value 120 comes from the second part of the example, devoted to recursion.
Following Types Through a Complete Transformation
The program FunctionsDemo.java contains almost all the chapter's ideas in a few lines. Let us reread it as we would read the path of a datum in a real application. The input " Java " enters clean, which returns "Java"; it then enters uppercase, which returns "JAVA". The predicate nonEmpty answers true. The length condition compares 4 with minimumLength, which is 3, and allows print.accept to execute. Printing JAVA: 4 is a side effect declared by the choice of BiConsumer. The program thus distinguishes between transformation of a value, a Boolean decision and an action that interacts with the outside world.
Let us instead follow " Go ": after strip we obtain "Go", then "GO"; the non-empty predicate is still true, but the length 2 does not reach the threshold 3. The string made of a single space becomes empty in the first transformation and is stopped by the predicate. If we modified the program to check length before strip, the spaces would count and the decision might change. The position of a filter in the pipeline is not only a possible optimization: it can be part of the meaning. This is why we formulate the contract in precise words, for example “a cleaned title of at least three characters”, before choosing the order of calls.
We can also replace the local threshold with a function returned by a method: Predicate<String> atLeastLength(int minimum) { return text -> text.length() >= minimum; }. If we request atLeastLength(3), the threshold is fixed while the text will vary at every call to test. The method's signature describes two different times: first we configure the rule, then we apply it. This is a case in which the closure is useful for modeling a choice, rather than merely showing a language mechanism. If the minimum value must change during execution, on the other hand, creating a new predicate or using an object with explicit state will be more honest than trying to circumvent the effectively final rule.
A Functional Contract for Validating, Not Only for Calculating
Imagine that a system accepts usernames. Today's required rules are “non-empty”, “at least four characters” and “without spaces”. We can represent them with three Predicate<String> values and compose them with and. First, however, we must decide what to do with null: calling isBlank() on null throws an exception. A first predicate text -> text != null protects the subsequent ones thanks to the short-circuit evaluation of and. At that point the set of conditions can be verified on null, " ", "anna" and "an na". Four inputs chosen to cover different cases are more instructive than a single valid string.
Predicate<String> present = text -> text != null;
Predicate<String> nonEmpty = text -> !text.isBlank();
Predicate<String> longEnough = text -> text.length() >= 4;
Predicate<String> withoutSpaces = text -> !text.contains(" ");
Predicate<String> validName = present.and(nonEmpty).and(longEnough).and(withoutSpaces);
The rule is not perfect: contains(" ") checks only the ordinary space, rather than every whitespace character. If the requirement is “no whitespace character”, a different check must be chosen and the characters that the domain considers forbidden must be defined. This observation is an example of transfer: composition works, but the real problem asks for a more accurate definition. It is also why a complex business rule may deserve a named method or object, rather than remaining an anonymous chain that nobody knows how to update.
A Function's Result Depends on Everything It Reads
The definition of a pure function seems simple as long as the parameters are immutable numbers. Take int total(List<Integer> values): if the method reads the list and calculates its sum without modifying it, it is pure with respect to a stable snapshot of the list. But if other code can modify the same list between two calls, the parameters have the same reference and yet different contents. Merely saying “the same arguments” becomes ambiguous. To reason about purity we must consider the observable state reachable through the arguments. An immutable copy constructed with List.copyOf can provide more stable input, provided that its elements also do not carry relevant mutable state.
Referential transparency is a useful mental test on a concrete expression. calculateVAT(100) can be replaced with its result only if the rate, rounding and other data read are established by arguments or known immutable values. If the method consults mutable configuration or the current date, two apparently equal calls can produce different results. We do not need to eliminate such functions from a program: we must make the dependency visible, for example by passing rate and date as arguments, and let the outer layer read configuration and the clock. This makes the core of the calculation verifiable again with repeatable examples.
Box – An Effect Does Not Mean an Error. Writing a file, sending an HTTP request or updating a counter are necessary effects in many applications. The problem is hiding them inside a function called
normalizeTextor in a predicate that seems limited to answering true/false. An appropriate name and type help, but a contract is also needed: when the effect occurs, how many times it can occur and how a failure is reported. These questions become decisive if behavior is handed to another API that controls the time of the call.
Purity, Immutability and Effects
A pure function produces the same result for the same arguments and does not change any state observable from outside. text -> text.strip() is a good example: String is immutable, and the transformation returns a value. Printing, on the other hand, is an intentional side effect: it writes to the program's output. It should not be treated as a defect that must always be eliminated; it should be placed where the reader can see it and where it does not surprise whoever reuses the function.
Referential transparency is the possibility, in a given context, of replacing a call with its result without changing the program's behavior. If sum(5, 5) is pure and returns 10, using 10 in its place does not change the result. If the function increments a global counter every time it is called, the substitution would lose that effect and would not be equivalent. In Java code, this test helps us recognize a hidden dependency before it makes a calculation difficult to predict.
Important note – Immutability of the Reference and of the Object. A
finalreference cannot be reassigned, but the object it points to may still be mutable. Writingfinalis not enough for a pure function: we must understand which objects are read or mutated and which effects can be observed from outside.
Pure functions are easier to test and compose because they do not depend on the order of undeclared calls. Nevertheless an application must read data, record events and communicate with the outside world. The practical criterion is to keep pure transformations where they help and confine effects to recognizable points, rather than claiming that Java or streams automatically eliminate effects.
Capturing Local Variables
In the program, the lambda does not read minimumLength directly, because the comparison is in the loop; however, we could write Predicate<String> longEnough = text -> text.length() >= minimumLength;. The lambda then captures the value of the local variable. Java requires a captured local variable to be final or effectively final: the word final can be absent, but after its initial assignment the variable must not be reassigned. If we wrote minimumLength++ later in the same method, the compiler would reject the capture.
The rule does not automatically make the captured object immutable. A lambda can have a final reference to a list and modify its elements, but this possibility should be used carefully: it makes the result depend on external state and can create problems in parallel flows. A closure, in the sense useful here, is behavior that retains access to values from the context in which it was created. In Java we must read this concept together with the rule for captured local variables and the distinction between reference and object.
Lambdas can appear inside loops, calls and assignments. They are not always the clearest form. If the body has many branches, several effects or a meaning deserving a name, an ordinary method often reduces the reader's work. A method reference is useful when it replaces an obvious lambda; it is not worth using if it forces us to decipher a signature without context.
Capture: Behavior That Retains Context
Let us return to the program's method add(int increment). increment is a local parameter: its ordinary visibility ends when the method returns. Yet the returned Operation can be executed after that return. The lambda continues to use the value needed for its calculation. This is the concrete situation for which we speak of a closure: behavior carries with it what it needs from the lexical context in which it was defined. There is no need to imagine that the method's whole stack remains alive. We need to understand which value was captured and which rules make that capture safe.
static Operation add(int increment) {
return (a, b) -> a + b + increment;
}
Operation withTwo = add(2);
int result = withTwo.execute(10, 3); // 15
increment is effectively final: after receiving its value, it is not reassigned in the method. If we added increment++; after the lambda definition, the compiler would reject the program. The rule also applies if reassignment is in a branch that seems unlikely to us: the compiler checks the method's structure. For a captured local variable, the lambda observes the value needed for its own execution, rather than a local slot that the caller can change later. The difference emerges especially when behavior survives the method that created it.
Instance variables follow a different path. In the CaptureDemo.java program, the object owns the field total; the method prepare(3) returns an IntSupplier that adds 3 to the field every time it is invoked. The two calls print 3 and 6. The local increment is stable, but the object's field changes: the lambda uses the same object through this. This is a lambda with an effect. It is legal and sometimes useful, but the calls are not interchangeable: the second depends on the first. In the presence of several threads, a synchronization rule will also be needed, the subject of the concurrency chapter.
IntSupplier next = account.prepare(3);
System.out.println(next.getAsInt()); // 3
System.out.println(next.getAsInt()); // 6
A static field is accessible in the same way as in an ordinary method, if visibility permits it. A lambda can read and modify it; this does not make it pure and does not trigger the effectively final rule for local variables. However, the fact that a modification compiles does not mean it is a good choice. A global counter used in a filter makes the result depend on evaluation order and difficult to reproduce. This is why, when a lambda is passed to a pipeline, we must declare whether it observes only the current element or uses changing state.
Box –
finalDoes Not Freeze a List. We writefinal List<String> names = new ArrayList<>();and thenConsumer<String> add = names::add;. The referencenamescannot be reassigned, but the list can be modified. The lambda is valid and produces an effect. If the same consumer were called by several threads without coordination, the wordfinalwould not protect the list's internal structure. The required protection depends on the shared object and its rules, rather than on the immutability of the local reference.
Lambda and Anonymous Class: What this Indicates
An anonymous class is a new object with its own this; a lambda uses the this of the class containing it. We can verify this without relying on an abstract definition. A class Label has a field name = "outer". Inside one of its methods we create an anonymous class with its own field name = "anonymous" and a method printing this.name. Then we create a lambda printing this.name. The first print is anonymous, the second outer. The lambda does not create a new scope for this as the anonymous class does.
Runnable anonymous = new Runnable() {
private final String name = "anonymous";
@Override public void run() { System.out.println(this.name); }
};
Runnable lambda = () -> System.out.println(this.name);
This fragment is valid inside an instance method of Label; it is not intended to sit in a static method, where there is no this for the outer instance. super in a lambda is also resolved in its enclosing lexical context. Another practical difference is that an anonymous class can implement an interface with several methods, whereas a lambda requires a functional target type. We should not mechanically turn every anonymous class into a lambda merely because the visible body is short: we check fields, methods, this, super and object identity.
When comparing lambdas and anonymous classes, we must distinguish guaranteed behaviour from performance and allocation details: the specification defines the observable behavior of lambdas, rather than promising a fixed allocation strategy valid for every JVM. The choice between anonymous class and lambda begins with the contract and readability. If a real profile demonstrates a significant cost in a hot spot, we measure that implementation on the relevant JVM and workload. In the absence of such data, an absolute claim about speed teaches a misleading shortcut.
Method References: Four Problems, Four Forms
When a lambda passes its own arguments to an existing method without adding logic of its own, we can often use ::. The method reference retains its target type: System.out::println is not a standalone type, but can be assigned, for example, to Consumer<String>. The four most useful forms are distinguished by who owns the method and where the receiver comes from.
The first form, ClassName::staticMethod, uses a static method. Integer::sum can implement BinaryOperator<Integer> because it receives two Integer values that Java converts to the method's int parameters and returns a result adaptable to Integer. In our program, LambdaPathDemo::sum implements the custom interface Operation. The signatures do not need to coincide as text strings: the compiler applies the compatibility rules for parameters and result, including permitted adaptations such as boxing and unboxing. If the types do not agree, the error occurs at compile time.
The second form, object::instanceMethod, already has a receiver. System.out::println retains the reference to System.out used to construct that method reference; the parameter that arrives at Consumer.accept becomes the argument of println. A domain example could be catalog::record assigned to a Consumer<Book> if catalog is an object with the method record(Book). Here the receiver is chosen when we prepare the behavior. If catalog is null, constructing the instance method reference produces an error: it is not equivalent to a postponed call on a possibly null reference.
The third form, ClassName::instanceMethod, does not yet have the receiver. The first argument of the functional interface becomes the object on which to call the method. String::length can become Function<String, Integer>: when apply("Java") is called, the received string is the receiver of length(). String::startsWith can become BiPredicate<String, String>: the first argument is the text to query, and the second is the prefix. Reading the two roles in the right order avoids reversing the question. The equivalent lambda form, (text, prefix) -> text.startsWith(prefix), is a simple test of the correspondence.
The fourth form, ClassName::new, calls a constructor. Supplier<ArrayList<String>> factory = ArrayList::new produces a new list at every get(), whereas Function<String, StringBuilder> create = StringBuilder::new uses the constructor receiving a string. We can also use an array constructor reference, String[]::new, with an interface receiving the size and returning an array. There is no need to memorize all the signatures: we look at the target type, identify the available arguments and check which constructor is applicable.
Guided verification. For
BiPredicate<String, String> startsWith = String::startsWith,startsWith.test("Java", "Ja")istrue; swapping the two arguments makes itfalse. ForFunction<String, Integer> length = String::length,length.apply("Java")is 4. If the method reference makes the argument order less visible, we use the explicit lambda. Readability is part of the teaching contract.
A reference to an overloaded method can be resolved by the target type, but sometimes several signatures remain applicable and the compiler reports an ambiguity. Overload ambiguity is a compile-time problem: the caller cannot unambiguously choose the signature. If we have two overloads process(Callable<String>) and process(Supplier<String>), the expression () -> "ok" is compatible with both. We can use a cast to the desired type, but distinct names for operations with different meanings are usually clearer and more stable.
Recursion: a Problem That Calls Itself
factorial in the program shows recursion: a method calls itself on a smaller problem. The case n == 0 stops the descent; for n > 0, the result is n multiplied by factorial(n - 1). For 5, the calls reach zero and climb back up producing 1, 1, 2, 6, 24 and 120.
Let us draw a triangle made of rows of dots: it allows us to see what changes between one case and the next. In the figure, T(n) is the total number of dots after adding row number n. It is not the geometrical area of a continuous triangle; it is a count of discrete units arranged as a triangle.
T(n), the dots of T(n − 1) are retained and a row of n dots is added. The different color of the last row in the fourth drawing shows the recursive step.The initial case is T(0) = 0: no rows, no dots. For a positive integer n, the rule is T(n) = T(n − 1) + n. In this formula, n is the number of dots in the new row, T(n − 1) is the total already built and the result is a count of dots, with no physical units. Following the steps in the figure, we obtain T(1) = 1, T(2) = 1 + 2 = 3, T(3) = 3 + 3 = 6 and T(4) = 6 + 4 = 10. The formula applies here to non-negative integer n; it does not describe a continuous measure or a negative input.
The complete program TriangularNumbersDemo.java directly translates the rule: for zero it returns zero; otherwise it adds n to the result of triangular(n - 1). For triangular(4), the JVM waits for the result of 3, which waits for 2, then 1 and finally 0. Climbing back up, the sums produce 1, 3, 6 and 10; these are precisely the four lines printed by main. Math.addExact reports an int overflow, but does not prevent stack exhaustion for very large values: these are two different limits. A loop version can calculate the same total with constant call depth. Even the closed formula n(n + 1)/2 requires attention to overflow of the product before division; the algebraic shortcut does not automatically remove the limits of Java types.
The two examples check different risks: TriangularNumbersDemo rejects a negative value and uses Math.addExact in the recursive addition; the factorial method of FunctionsDemo uses Math.multiplyExact in the product. In both cases an overflow exception prevents a silently incorrect integer result. However, this is not enough to make recursion suitable for enormous numbers: many nested calls consume stack, and a case without a stop can cause StackOverflowError. Java does not promise a general transformation of tail recursion into a loop. For very large linear sums and products, a loop may be simpler and more cautious.
The composition encountered with andThen builds a transformation from smaller operations; recursion builds a solution from smaller problems. In both cases the step must be read and verified: in composition, the order of functions matters; in recursion, the case stopping the calls matters. compose applies functions in the opposite order in the written expression compared with andThen. The comparison prepares us to check the cost of recursion without turning the two techniques into synonyms.
Recursion: Costs, Limits and Alternatives
Figure 16.2 gave us the base case T(0) = 0 and the step T(n) = n + T(n - 1) for n > 0. Now let us look at the cost of those calls. If the base case is missing or the step does not approach it, calls continue until the stack is exhausted. If n is negative, the mathematical rule chosen in the chapter does not define it: the program must reject that input rather than descend indefinitely.
For T(4), the call stack contains, in order, T(4), T(3), T(2), T(1), T(0). Then the results climb back up: 0, 1, 3, 6, 10. The JVM retains the point at which each call must resume and its local data. This explains why the memory used grows with depth, even though every line of code is short. In the TriangularNumbersDemo.java program, Math.addExact catches exceeding the limit of int; it does not catch an excessively deep stack. These are two separate problems: one concerns the value calculated, and the other the structure of execution.
An iterative version maintains an accumulator: it starts from zero and adds 1, 2, ... n. For n = 4 it obtains the same intermediate values as the recursive climb without keeping four calls waiting. The closed formula T(n) = n(n + 1)/2 is derived by placing two equal triangles together: together they form a rectangle with sides n and n + 1, so a triangle contains half its dots. It is unwise to naively translate the formula into int with n * (n + 1) / 2, because the intermediate product can overflow even when algebraic reasoning would allow division first. For large inputs we choose a suitable type, check the operations and consider memory and time limits. The objective here is to learn to choose a representation, rather than declare recursion always better or always worse.
The first program's factorial function has another base case, 0! = 1, and for n > 0 uses n! = n × (n-1)!. In the code, Math.multiplyExact warns when a result no longer fits in int. Let us write a small table by hand: 0! = 1, 1! = 1, 2! = 2, 3! = 6, 4! = 24. Then we compare it with execution. This verification is more instructive than an isolated final print, because it tells us where the result could diverge from the rule. The transfer is a method traversing a tree: there too a base case is needed, for example an absent node, and a step visiting smaller subtrees.
Partial Application and Currying, When They Are Really Needed
Suppose a shop must often apply a discount of 10 percent. A general function calculate(price, percentage) receives two values; a function tenPercentDiscount retains the percentage and receives only the price. In Java we can construct it with a method returning UnaryOperator<BigDecimal> or with a custom interface, provided that the monetary rules are defined: rounding, scale and the meaning of the percentage. The advantage is that the “10 percent” rule becomes named behavior that can be reused at points in the program where only the price changes.
Currying in the strict sense transforms a function of two arguments into a function receiving one and returning another function: Function<A, Function<B, R>>. Partial application instead fixes some arguments of a function and produces a more specific one. In everyday Java use the two concepts are often brought close together, but they are not identical. The method add(2) is a practical example of fixing a value in returned behavior; we do not need to pretend that every method with several arguments must be rewritten as a chain of functions. BiFunction is often the clearest signature for an ordinary binary operation.
static Function<Integer, Integer> sumWith(int increment) {
return value -> value + increment;
}
Function<Integer, Integer> addThree = sumWith(3);
int seven = addThree.apply(4);
Let us follow the data: sumWith(3) does not yet calculate the final result; it prepares a function remembering 3. apply(4) provides the second value and produces 7. We can verify addThree.apply(10) == 13 without recreating the function. The transfer to a validation rule is similar: lengthAtLeast(8) can return a Predicate<String> checking many candidate passwords according to a threshold chosen once. If the rule is not reused or the nested call becomes less readable than a simple method with two arguments, the intermediate step adds no value.
Pipelines and Monads: a Necessary Distinction
Calling any class of chainable functions a “monad” is too broad a simplification: many functions can be chained without forming a monad. For our path, it is enough to understand a pipeline: the output of one step becomes the input of the next, with contracts that make composition possible. clean.andThen(uppercase) is a pipeline of two transformations; a Stream pipeline adds a source and a terminal operation. Chaining alone does not promise parallelism: sequential streams perform the work in the calling thread, and steps can be fused or optimized by the implementation.
Further reading – For Those Who Will Encounter the Term “Monad”. In functional programming the term concerns a disciplined way of composing calculations that produce values in a context, with precise operations and laws.
Optional, for example, represents a possibly absent value and allows transformations that respect that context to be chained throughmapandflatMap. But knowing the name is not a precondition for usingOptionalcorrectly; and saying that every pipeline is a monad would be false. Here we first learn to recognize the concrete problem of an absent value and the contract of the operations. The theoretical concepts will become useful when we have real cases to compare them with.
Optional: a Result That May Be Missing
A method findBook(String code) may find nothing. Returning null forces every caller to remember a convention not expressed in the type; forgetting it leads to NullPointerException. Returning Optional<Book> puts absence in the signature. Optional.empty() represents the absent case; Optional.of(book) requires a non-null value; Optional.ofNullable(book) accepts the null case when we must adapt existing code. We do not use Optional.ofNullable to indiscriminately hide design errors: we use it when absence is a normal and declared outcome.
Optional<String> title = Optional.of(" Java ");
String displayed = title.map(String::strip)
.filter(t -> !t.isEmpty())
.orElse("untitled");
map transforms the value if present and leaves the Optional empty if it is not. filter retains the value only if it passes the condition. orElse provides an alternative value. If the alternative requires work, orElseGet(() -> calculateAlternative()) calculates it only when needed; the argument of orElse, being an ordinary Java expression, is instead evaluated before the call. orElseThrow is appropriate when absence violates an already checked contract or when an explicit exception communicates the problem. Calling get() without checking presence returns the risk to the caller and loses much of the clarity obtained with the type.
Optional is not a collection to use for every field or parameter. It is particularly useful as the return value of a search. In Chapter 18 we will encounter findFirst and findAny, which can find no elements and therefore return Optional. The correct question is not “how do I extract the value immediately?”, but “what must the program do when the value is missing?”. A catalog can display “not found”; a payment process can stop with an error; an exploratory search can continue. These are domain decisions, rather than API details.
From Optional Values to Transformation Functions
An Optional<String> can contain the title found by a search. map(String::strip) cleans it if present, while flatMap is useful when the called function already returns an Optional. Suppose findAuthor(String title) returns Optional<Author>. If we write title.map(this::findAuthor), we obtain an Optional<Optional<Author>>: a possible container around another possible container. flatMap(this::findAuthor) retains only one level of absence. This step anticipates the same difference between map and flatMap in streams: we always look at the type produced by the inner function, rather than just the outer method's name.
The choice of alternative in Optional is part of the solution. orElse("unknown") is suitable if the replacement label is already available; orElseGet(this::loadLabel) postpones potentially expensive work until the Optional is empty. If absence is an error, orElseThrow(() -> new IllegalArgumentException("missing title")) makes the failure explicit. If we only need to act when there is a value, ifPresent accepts a Consumer. The choice is not “which method is the most modern?”, but “which response does the problem require in presence and in absence?”.
There are also deliberate limits: Optional should not automatically become a field of every entity, or a way of accepting null everywhere. Some serialization and persistence libraries have their own conventions; a signature with Optional does not replace them. Its greatest value is in the call to a method that can legitimately fail to find a result. Hence the connection with findFirst in the next chapter: absence is an expected outcome and the caller must handle it.
Style Choices That Protect Meaning
When a lambda is three screens long, the reader has to reconstruct both the meaning of the operation and all its branches. A named method such as calculateFinalPrice can make the pipeline clearer, provided the name is accurate and the body remains verifiable. A method reference should be preferred when it immediately explains the action; String::strip is clear, whereas a chain of references to overloaded methods with complex generics can require more effort than the explicit lambda. The code should allow someone reading it to follow input data, transformation and result without guessing.
For an important domain rule, a small custom interface can be better than Predicate<Order>: DiscountRule or OrderCheck can express an intention that the generic test does not communicate. However, creating a new interface for every one-line lambda produces a lot of code without improving the model. First we try the standard interfaces; if the name or the exception contract is not enough, we define the domain type. Here too the path is problem, choice, verification: a caller must understand from the signature which behavior to provide and what to expect as output.
Overloading methods that accept similar functional interfaces requires attention. execute(Supplier<String>) and execute(Callable<String>) both receive a parameterless lambda producing a string; the call execute(() -> "ok") is ambiguous. A cast resolves the local case, but two different names can clarify the different semantics of the operations. Furthermore, Callable.call can declare Exception, whereas Supplier.get cannot: even when the expression looks identical, the error contract changes. This is a good example of how a functional signature is more than a syntactic convenience.
To evaluate whether a lambda is suitable for an API, let us ask whether it can be called zero, one or several times, whether order is guaranteed, whether it can execute in another thread and whether the caller expects a function without effects. Comparator.compare, for example, can be called many times by a sort. A comparator that changes its answer based on a counter produces an inconsistent order. A Predicate in a stream can be skipped in some optimizations. A Supplier given to a cache can be invoked only when the value is missing. Understanding these conditions is worth more than memorizing every form of ->.
Verification and transfer. Return to the initial problem of prices: write an
Operationfor the difference, pass it tocalculateand verify the result with values you choose. Then try replacing it withInteger::sum; explain why the calling method does not change. Finally, transfer the model to a list of titles: the common work traverses the titles, while the variable behavior decides which to accept. If the decision must consult an external archive, make that effect visible and explain how you will verify an access error.
A Transfer Test: Classifying Documents
An archive receives textual descriptions and must assign a category based on the contents. We can separate three responsibilities: a Function<String, String> cleans the text, a Predicate<String> checks that it is usable and a Function<String, Category> classifies it. Before writing lambdas, we decide the cases: a null description, spaces only, valid text but unknown category. If classification can fail without the data being incorrect, the return type could be Optional<Category>. If instead a remote service decides the category, the operation carries I/O, latency and errors; hiding it in a lambda called classify does not remove those responsibilities.
The first verification can be entirely local: three strings, three expected results, no network. The second can replace the classifier with a fake implementation returning known categories. This shows the benefit of passing behavior as an argument: we can change the rule without duplicating the cleaning and validation path. The transfer from the price problem to the document problem is therefore real: the stable structure traverses the data, the variable part is typed behavior and the checks test both parts.
Three Reading Errors to Recognize Before They Become Defects
The first error is confusing syntactic brevity with purity. x -> { counter++; return x * 2; } is a short lambda, but depends on an external field and modifies it. x -> x * 2 is a transformation without that effect. When reading behavior passed as an argument, we do not stop at the arrow: we identify all the values read and written. If it is a calculation rule, we ask whether two calls with the same input can be interchanged without changing the application's result. If the answer is no, we document the dependency and verify the order of calls.
The second error is believing that @FunctionalInterface is mandatory for using a lambda. An interface with a single abstract method is functional even without the annotation. We annotate it because we want to protect the project's intention: if the interface evolves, the compiler must warn us that existing lambdas would lose their contract. This is the same reason that @Override helps when we implement a method: the explicit declaration allows the compiler to check a choice that might otherwise remain only in our heads.
The third error is attributing more clarity to a method reference than it has. String::replaceAll requires knowing that the first argument of the target function becomes the string on which to call the method, while the others become the call's arguments. For a reader still learning this mechanism, (text, expression, replacement) -> text.replaceAll(expression, replacement) can be clearer. Furthermore, replaceAll interprets the first parameter as a regular expression, rather than literal text; if the problem requires a literal replacement, replace is another operation. The shorter form does not correct a wrong semantic choice.
Verifying Functions with Discriminating Cases
For sumWith(3), we try zero, a positive number and a negative one. The expected result is respectively 3, 7 for input 4 and 1 for input -2. These cases verify that the fixed value is actually added and is not confused with a multiplier or a threshold. For validName, we try null, an empty string, four letters without spaces and four characters with a space. The test does not aim to repeat the lambda's body: it aims to represent different classes of input for the problem.
When a function is composed with another, we add a case in which changing the order changes the result. If two transformations commute for all the test data, an incorrect order would pass unnoticed. This is why the example with the prefix and removing the first character is pedagogically stronger than strip followed only by toUpperCase. The rule transfers to unit conversions, normalizations, tax calculations and validations: choosing an input that distinguishes two plausible implementations makes verification informative.
In Chapter 17 we will encounter the collections that store data; in Chapter 18 we will use the typed behaviors of these pages in pipelines. The distinction built here remains valid in both: a function describes a transformation, while the API receiving it decides when and how many times to invoke it.
To Verify
Compile and run FunctionsDemo.java, LambdaPathDemo.java and CaptureDemo.java with JDK 25. Change minimumLength from 3 to 2 and predict which new line will appear. Then replace String::strip with the equivalent lambda and verify that the output remains the same. Before running CaptureDemo, predict why the second call gives a different result from the first. To check recursion, write the calls of factorial(3) on paper before running them. Finally, try factorial(-1) in a copy of the program and explain which contract has been violated.