Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Fundamentals › Java

Lambdas

What does a lambda shorten?

Why it exists — To pass one piece of work to other code, such as the work to hand to a new thread or the rule for sorting a list, before lambdas (up to Java 7) you had to write an anonymous class that implements Runnable or Comparator over several lines, with new and the method declaration, and the one line that mattered was buried among them. Lambdas, which came in Java 8, rely on the fact that if an interface has only one method to implement, the compiler can tell which method the work belongs to, so you write only the parameters and the work, joined by an arrow.

Where it's used today — You use it wherever Java takes some work, such as new Thread(() -> ...), which passes the work to hand to a new thread, list.sort((a, b) -> a.compareTo(b)), which passes the rule for sorting a list, list.removeIf(n -> n < 0), which removes the elements that match a condition, and filter and map of a stream. When the work gets long over several lines, you write it separately as a named method and sometimes pass that method with a method reference (::).

A lambda is a short piece of code written with an arrow (->). () -> System.out.println("Working") is a short way to write "an object that implements an interface with only one method to implement". This lab looks at it through two interfaces that Java provides. Runnable (in the java.lang package) has one method to implement, run(), and what new Thread(…) takes is this Runnable. Comparator (in the java.util package) has one method to implement, compare(a, b), and what list.sort(…) takes as the sorting rule is this Comparator. You compile and run the same code to see whether writing the lambda out as an anonymous class or a named class gives the same result, whether the code after the arrow runs on the line where the lambda is written or when it is called, and who calls that code (r.run() in my code, a new thread, or sort). Finally, you see that a lambda cannot be used when an interface you made yourself has two methods.

Checked against real execution · On the PC used to write this lab, 21 combinations (Runnable, Thread, List.sort, and the Task we made) were compiled with javax.tools on JDK 21 and run with java Main, and checked (verify/plain/LambdaBasicProbe.java, cmp_lambda_basic.js)

Concepts in this lab

Lambda expression
This is a syntax, introduced in Java 8, for writing a function with no name in a compact way. It has the form (parameters) -> body, and it is used as the implementation of a functional interface, which has only one abstract method. It lets you pass behavior (code) to another method as if it were a value.
Functional interface
Why it exists — Java has no separate type that represents just a function, so a type was needed for the variables and parameters that receive a lambda. A functional interface uses an interface with only one abstract method as that type, so existing interfaces such as Runnable and Comparator can receive a lambda as they are.
Where it's used today — It is used when you write a method that receives behavior as a parameter, as the stream's filter receives a Predicate and map receives a Function. When you define one yourself, you add @FunctionalInterface so that the compiler checks that there is only one abstract method.
This is an interface with only one abstract method (a redeclared method of Object such as equals is not counted, and any number of default and static methods is allowed), and it is a type to which a lambda expression or a method reference can be assigned. The java.util.function package predefines types such as Function (takes an input and returns a result), Supplier (supplies a value), Consumer (consumes a value), and Predicate (tests a condition).
Runnable
Why it exists — From Java 1.0, a way was needed to hand a thread the message "please do this work". An interface that fixes the work as one method, run, was provided so that Thread only has to call run, whatever class the object belongs to.
Where it's used today — You pass a Runnable when you give work to a new thread with new Thread(() -> ...), and when you hand work to a thread pool with execute(...) or submit(...) of ExecutorService. Today it is usually written as a lambda.
Runnable is an interface that Java made in advance in the java.lang package, and it has only one method with its name written and no body, void run(). It has only one method to implement, so it is a functional interface (it has @FunctionalInterface), and that is why you can create an object that implements it with a lambda, as in Runnable r = () -> System.out.println("Working");. You can also write the same thing as a class, such as the anonymous class new Runnable() { public void run() { … } } or class Work implements Runnable. The body of run does not run on the line where the lambda or the class is written; it runs when someone calls run. If my code calls r.run() directly, it runs on the thread that is running now, and if you pass it to new Thread(r) and then call start(), the newly started thread calls run.
start() and run()
Why it exists — The way to create a thread differs for each operating system, so to create one yourself you would have to call that operating system's features. start() leaves this job to the Java virtual machine (JVM), and the work to do is written in run() as an ordinary method, so that the task code and the creation of a thread are separated.
Where it's used today — In a short example or a test, you start a thread right away with new Thread(task).start(). If you write the work as a Runnable or a lambda, you can also hand the same code to an ExecutorService and run it on a thread of a pool.
These are two methods of Thread: start() creates a new thread and has that thread execute run(), and run() is an ordinary method that holds the work the thread is to do. So if you call run() directly, no new thread is created, and the calling thread runs that code in order. start() can be called only once on a Thread object, and a second call throws an IllegalThreadStateException. To run the same task again, create a new Thread object.
Comparable and Comparator
These are the two ways to define the order of objects. Comparable is an interface that a class implements itself, and its single method, compareTo, defines the natural ordering of that class. A Comparator is a way of comparing that is created separately, outside the class, and it lets you sort the same objects by a different sort key each time. Both return a negative number if the first object comes first, 0 if the order cannot be decided, and a positive number if it comes later. Returning the difference of two numbers as it is can flip the sign through overflow, so use Integer.compare or Comparator.comparingInt.
Anonymous class
Where it's used today — Use it when you implement an interface or abstract class with two or more methods right on the spot where it is used only once, or when you need an implementation that has fields. For an interface with only one abstract method, a lambda is usually used now.
This is a class that is given no name and from which one object is created right where the class is declared. You write its body in braces after the name of an interface or a class, as in new Runnable() { ... }, and the result is an object that implements that interface or extends that class. Its advantage is that you do not have to create a separate file for a small implementation that is used only once. Inside an anonymous class, this refers to that newly created object, which is different from a lambda expression, where this refers to the outer object. When the code is compiled, a separate class file is produced whose name is the name of the outer class followed by a number, such as Outer$1.

Try these

Running with the default settings

  1. javac compiles it. This code has no interface declaration. Runnable is an interface that Java made in advance in the java.lang package, so you can use it without an import, and it has only one method with its name written and no body, run(). Whatever implements Runnable has to write only run.
  2. The compiler reads the line Runnable r = () -> System.out.println("Working"); The type of the variable on the left is Runnable, so the code after the arrow is read as the work of the method that Runnable has to implement. Runnable has only one method to implement, run, so that code is decided to be the work of run. This is why you do not have to write the method name. The () before the arrow means that run takes no values. Compiling is not running, so the code after the arrow does not run.
  3. Compiling succeeds, and the Main class file to run is created.
  4. You run it with java Main. main starts, and the line Runnable r = () -> System.out.println("Working"); runs. This line creates "an object that runs the code after the arrow when run is called" and makes the variable r refer to that object. The code after the arrow does not run on this line, so "Working" has not been printed. What the line that writes the lambda does goes only as far as creating an object that holds the work.
  5. System.out.println("Ready") runs and prints Ready. The object has already been created, but run has not been called even once.
  6. r.run() runs. This is the line where my code (main) calls run directly. run of the object the lambda made, which the variable r refers to, is called, and at that moment the code after the arrow System.out.println("Working") runs. "Working" came after "Ready". It ran at the moment it was called, not where the code was written. There is no new thread; the main thread, which was running main, runs run as it is.
  7. main ends. The output is Ready, then Working.

Result of this run

Code

public class Main {
    public static void main(String[] args) {
        // Lambda: write what run should do after the arrow. It does not run on this line
        Runnable r = () -> System.out.println("Working");
        System.out.println("Ready");
        r.run();
    }
}

Assumptions of this model

The compiler and runtime are JDK 21.0.12.1 (javac 21). For all twenty-one combinations (for each of the Runnable variable, the new thread, and the Task we made, 3 ways of writing it and whether the calling line is present or not, and for the sorting rule, 3 ways of writing it), source that is the same as the code on the screen (identical text, line by line) was compiled with javax.tools, and for those that compiled, java Main was run in a separate process and the result was checked against the standard output that was captured. What was checked is whether compilation succeeded, the diagnostic code of the error (the "incompatible types: Task is not a functional interface, multiple non-overriding abstract methods found in interface Task" of compiler.err.prob.found.req is translated as "Task has two methods to implement, so it cannot be used as a lambda"), the number of errors and the line where the error occurred, whether the Main class file was created, and the output when run. The facts that the step sentences rely on were checked separately by running. Runnable is an interface in the java.lang package and Comparator is an interface in the java.util package, and apart from the methods of Object, each has only one method with no body, run and compare respectively, and both have @FunctionalInterface (Comparator also has equals, redeclared with no body). Thread has a constructor that takes a Runnable, and List has a sort that takes a Comparator. Nothing was printed right after the line that writes the lambda, the anonymous class, or Work, and in all three cases the object implemented Runnable (the lambda was a hidden class on this JDK, the anonymous class was Main$1, and Work was an object of the Work class). The name of the thread that ran the work was main for r.run() and Thread-0 for th.start(). When these three names were sorted, sort called compare 4 times, and the first call was compare("Alice", "Carol"). The number of calls and the order are not set by the specification; they were observed in the sorting implementation of this JDK. For the API documentation, I read the documentation attached to the source of the same JDK directly. Runnable is a functional interface whose functional method is run(); the task of Thread(Runnable task) is the object whose run method is called when this thread is started, and if you give no name, a name made of "Thread-" followed by an integer is given automatically; start() makes this thread begin execution, and a thread can be started only once. The virtual machine begins to exit only when all the started non-daemon threads have ended, and a thread that was not started does not prevent the exit (the Thread class documentation). List.sort sorts the list in the order set by the given Comparator, and Comparator.compare returns a negative number if the first argument is less, 0 if they are equal, and a positive number if it is greater. For the language rules, I followed the Java Language Specification (Java SE 21), Section 15.27 (lambda expressions), Section 15.27.3 (a lambda has a functional interface as its target type in an assignment or invocation context), Section 15.27.4 (evaluating a lambda creates an object, and the body runs when its method is called), Section 9.8 (a functional interface is an interface that, apart from the methods of Object, has only one abstract method), and Section 15.9.5 (anonymous classes). I read only part of the relevant sections of the specification, as a summary, and did not read the whole text. The kind of error, the number of errors, and the line where it occurs are not set by the specification; they were observed on this javac. This lab covers only "a lambda is a short way to write an object that implements an interface with only one method to implement" and when and by whom its work is run. How this of a lambda differs from that of an anonymous class, and the rules for using a local variable of the enclosing code inside a lambda, are not covered. Method references and Supplier, Predicate, and Consumer of java.util.function are covered in the in-depth lab "Lambda expressions and functional interfaces", and the difference between calling run() directly and start() is covered in "Creating threads and thread states".

Previous lab: List and Map · Next lab: Streams

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these