Lambda Expressions and Functional Interfaces

What is a Lambda Expression?

A lambda expression is a short way to write a method.

It is used mostly when you want to pass behavior (a block of code) as data.

Real-life Example

Imagine a remote control. You can press a button to turn on the TV, turn on a fan, or start the AC.

You just change the behavior of the button.

Lambda expressions are like giving that behavior to a method.

Basic Syntax

(parameters) -> { code block }

Example:

(int a, int b) -> { return a + b; }

This means: "take two integers, and return their sum."

Functional Interfaces

A functional interface is an interface with only one abstract method.

You can use lambda expressions with these interfaces.

Example:

@FunctionalInterface
interface Greeting {
    void sayHello();
}

Now, let’s use a lambda expression:

Greeting g = () -> System.out.println("Hello!");
g.sayHello();

Simple, right?

Built-in Functional Interfaces

Java gives us some ready-to-use functional interfaces.

Examples

Consumer<String> printer = (s) -> System.out.println(s);
printer.accept("Printing from Consumer!");
Supplier<Integer> randomSupplier = () -> 4; // Always gives 4 :)
System.out.println(randomSupplier.get());
Function<String, Integer> lengthFunction = (str) -> str.length();
System.out.println(lengthFunction.apply("Apple"));
Predicate<Integer> isEven = (x) -> x % 2 == 0;
System.out.println(isEven.test(10));

Why Use Lambdas?

List Example

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println("Hi " + name));

Conclusion

Lambda expressions help you write short and clean code.

Functional interfaces work with them easily.

Practice with small examples, then try real projects!