What is Lambda Expression in java 8?

In Java 8, a Lambda Expression is a concise way to represent a block of code as an object, especially when working with functional interfaces.

It allows us to pass behavior as a parameter, instead of writing bulky anonymous inner classes. A lambda expression essentially defines what to do, not how to structure it, which makes the code cleaner and more readable.

Lambda expressions work only with functional interfaces, which are interfaces that have exactly one abstract method—like Runnable, Comparator, or Callable.

For example, instead of writing a full anonymous class, we can use a lambda to directly express the logic. This makes Java more expressive and brings it closer to a functional programming style.

Overall, lambda expressions help reduce boilerplate code, improve readability, and make it easier to write parallel and stream-based code in Java 8

An anonymous class is a class without a name that is used to provide an immediate implementation of an interface or abstract class.It is mainly used when we need to override methods for one-time use

So:

  • No class name
  • Created and used in the same place
  • Mostly used before Java 8 instead of lambdas

Example: Using Lambda with Runnable

Before Java 8 (Without Lambda)

public class Test {
    public static void main(String[] args) {

        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println("Task is running");
            }
        };

        Thread t = new Thread(task);
        t.start();
    }
}        

🔹 Problem: Too much boilerplate code for a small logic.

Java 8 (With Lambda Expression)

public class Test {

    public static void main(String[] args) {

        Runnable task = () -> {

            System.out.println("Task is running");

        };

        Thread t = new Thread(task);

        t.start();

    }

}        

What changed?

  • No class
  • No implements
  • No @Override
  • Only business logic

Why Lambda Works Here?

  • Runnable is a functional interface
  • It has only one abstract method: run()
  • Lambda provides the implementation directly

To view or add a comment, sign in

More articles by Vinothkumar P

Explore content categories