unkletayo
20

How Java treats functions as values

How Java represents behavior as a value, what functional interfaces are, and how lambdas connect to the type system.

Adetayo Akinsanya2026-10-136 min read

  • Java
  • Core Java
  • Lambdas
  • Functional Interfaces
  • Method References

Part 20 of the series.Read Generics: erasure, raw types, and what the compiler actually does (Part 19) first if you have not.

In this article (7 sections)
  1. Functional interfaces
  2. Lambda syntax
  3. Method references
  4. Variable capture
  5. Common functional interfaces in java.util.function
  6. Lambdas versus anonymous classes
  7. Prediction exercise

A sorting method needs to know how to compare two elements. One way to pass that knowledge: a class that implements a comparison.

Comparator<String> byLength = new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return Integer.compare(a.length(), b.length());
    }
};

List<String> words = new ArrayList<>(List.of("banana", "fig", "apple"));
words.sort(byLength);
System.out.println(words);  // [fig, apple, banana]

This works, but it is six lines for a single comparison. The object itself carries no state; it only carries behavior. Java 8 introduced a shorter way to express the same thing:

Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());
words.sort(byLength);

One line. Same result. This is a lambda expression: a compact syntax for creating an instance of an interface that has exactly one abstract method.

Functional interfaces

A functional interface is an interface with exactly one abstract method. Comparator<T> qualifies. Runnable qualifies (its one abstract method is run()). Comparable<T> qualifies.

An interface with two abstract methods is not functional, because a lambda has only one body to fill. The compiler rejects a lambda where a non-functional interface is expected.

The @FunctionalInterface annotation marks an interface as intentionally functional:

@FunctionalInterface
public interface Validator<T> {
    boolean isValid(T value);
}

The annotation is optional but useful. If someone accidentally adds a second abstract method to Validator, the compiler reports an error at the annotation rather than at every lambda that uses it.

Lambda syntax

The basic form is (parameters) -> body:

// No parameters
Runnable r = () -> System.out.println("running");

// One parameter (parentheses optional)
Validator<String> notEmpty = s -> !s.isBlank();

// Two parameters
Comparator<Integer> descending = (a, b) -> b - a;

// Block body for multiple statements
Comparator<String> complex = (a, b) -> {
    int byLength = Integer.compare(a.length(), b.length());
    if (byLength != 0) return byLength;
    return a.compareTo(b);
};

The parameter types are inferred from the functional interface. When the body is a single expression, its value is returned implicitly. A block body needs an explicit return statement.

Method references

A method reference is a shorthand for a lambda that only calls a single existing method:

// Equivalent forms
words.forEach(word -> System.out.println(word));
words.forEach(System.out::println);

There are four kinds:

Static method: ClassName::methodName

// (s) -> Integer.parseInt(s)
Function<String, Integer> parse = Integer::parseInt;

Instance method on a specific object: instance::methodName

String prefix = "log: ";
// (s) -> prefix.concat(s)
Function<String, String> addPrefix = prefix::concat;

Instance method on the lambda’s first parameter: ClassName::methodName

// (s) -> s.toUpperCase()
Function<String, String> upper = String::toUpperCase;

Constructor: ClassName::new

// (s) -> new StringBuilder(s)
Function<String, StringBuilder> build = StringBuilder::new;

Method references are a readability choice. Use them when the method name communicates intent clearly. If the lambda does anything beyond a single method call, write it out.

Variable capture

A lambda can read variables from the surrounding scope. The variable must be effectively final: assigned exactly once and never reassigned after that.

int minLength = 4;
Validator<String> longEnough = s -> s.length() >= minLength;  // captures minLength

minLength is captured by value, not by reference. The lambda holds a copy of the value at the moment of capture. Modifying minLength after the lambda is created would be a compile error (effectively final rule), so the copy is always correct.

int count = 0;
Runnable r = () -> count++;  // compile error: count is not effectively final

This restriction comes from the way lambdas are implemented. A lambda does not hold a reference to the enclosing stack frame; it captures copies of the values it needs. Allowing mutation of a local variable would require storing the variable on the heap, which is what anonymous classes do with field capture. Java chose the simpler rule: if you need a mutable captured value, use an array or a wrapper class as a one-element mutable container:

int[] count = {0};
Runnable r = () -> count[0]++;  // captures the array reference (effectively final)
r.run();
System.out.println(count[0]);  // 1

Instance fields (this.count) and static fields can be read and modified from within a lambda freely. Only local variables are constrained by the effectively-final rule.

Common functional interfaces in java.util.function

Java provides a set of generic functional interfaces for the most common shapes:

Supplier<T>: no argument, returns T. () -> new ArrayList<>().

Consumer<T>: takes T, returns nothing. item -> log(item).

Function<T, R>: takes T, returns R. s -> s.length().

Predicate<T>: takes T, returns boolean. s -> s.isEmpty().

BiFunction<T, U, R>: takes T and U, returns R. (a, b) -> a + b.

UnaryOperator<T>: takes T, returns T. A Function<T, T> with a clearer name. s -> s.trim().

BinaryOperator<T>: takes two T, returns T. A BiFunction<T, T, T> with a clearer name. (a, b) -> a + b.

The package also has primitive specializations: IntSupplier, LongFunction<R>, IntUnaryOperator, and so on. Use them when the type involved is a primitive; they avoid the autoboxing that the generic versions require.

Lambdas versus anonymous classes

A lambda creates an instance of a functional interface. An anonymous class also creates an instance of an interface (or abstract class). They overlap, but they are not identical.

The key difference is this. Inside an anonymous class, this refers to the anonymous class instance. Inside a lambda, this refers to the enclosing instance. If you need this inside the behavior, you need an anonymous class.

// 'this' inside lambda refers to the enclosing class instance
Runnable r = () -> System.out.println(this.getClass().getName());

// 'this' inside anonymous class refers to the anonymous class
Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println(this.getClass().getName());  // anonymous class
    }
};

Lambdas also cannot extend a class; they can only implement a functional interface. Anonymous classes can extend a class or implement any interface.

Another difference: each anonymous class new Foo() { ... } always creates a new class. Lambdas are compiled differently; the JVM may share class definitions across lambda instances and may elide allocations when the lambda captures nothing. In practice, prefer lambdas for their brevity and clarity; use anonymous classes only when you need this to refer to the anonymous instance or when implementing a non-functional interface.

Prediction exercise

List<String> words = List.of("apple", "fig", "banana", "date");
String result = words.stream()
    .filter(w -> w.length() > 3)
    .sorted(Comparator.comparingInt(String::length).reversed())
    .findFirst()
    .orElse("none");
System.out.println(result);

Work through the steps: which words pass the filter, what order does sorted produce, and what does findFirst return? The next article covers streams in full: how the pipeline processes elements lazily, what map and flatMap do, and how collectors aggregate results. Streams and Optional continues from here.

Questions or corrections

Found a mistake or have a question about this breakdown? Reach out directly.

Reply on X (@unkletayor)Email feedback