Java - Lambda Expressions & Functional Interfaces in Java

What are Lambda Expressions?

 

A lambda expression is a short and simple way to write anonymous functions (functions without names) in Java.
It was introduced in Java 8 to make code more concise and readable, especially when working with collections and streams.

In simple words:
A lambda expression lets you write less code when implementing a method that is used only once.

Basic Syntax

(parameters) -> expression

OR

(parameters) -> {

    // multiple statements

}

Example:

Runnable r = new Runnable() {

    public void run() {

        System.out.println("Running");

    }

};

With Lambda

Runnable r = () -> System.out.println("Running");

✔ Shorter
✔ Easier to read

Functional Interfaces

 

A functional interface is an interface that has only one abstract method.
Lambda expressions are used to implement these interfaces.

Common examples

Runnable

Comparator

Callable

You can also create your own:

interface MyInterface {

    void display();

}

Using lambda:

MyInterface obj = () -> System.out.println("Hello");

obj.display();

Built-in Functional Interfaces

 

Java provides many ready-to-use ones:

Predicate<T> → returns true/false

Function<T,R> → takes input, returns output

Consumer<T> → accepts input, no return

Supplier<T> → returns value, no input

Example:

Predicate<Integer> p = x -> x > 10;

Advantages of Lambda Expressions

  • Reduces code length

 

  • Improves readability

  • Supports functional programming style

  • Works well with Streams API

 

  • Encourages cleaner collection processing

    When to Use Lambdas

    • Sorting collections

    • Event handling

    • Passing behavior as parameters

    • Stream operations

In Simple Words

Lambda expressions provide a compact way to represent small pieces of functionality, while functional interfaces define the structure those lambdas must follow. Together, they make Java code shorter, modern, and easier to work with.