Java officially supported lambda expressions when Java 8 was released in 2014. Lambda expressions are shorthand implementations for single abstract method (SAM) classes. In other words, they are quick ways to pass functional arguments instead of anonymous classes.
Prior to Java 8, you might have leveraged anonymous classes to implement interfaces, such as Runnable
, on the fly as shown in the following code snippet:
public class Launcher { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("run() was called!"); } }; runnable.run(); } }
The output is as follows:
run() was called!
To implement Runnable
without declaring an explicit class, you had to implement its run()
abstract method in a block immediately after the constructor. This created a lot of boilerplate and became a major...