Skip to content

🔥 Java Lambda Expressions – Write Clean and Functional Code

🧠 Introduction

Starting with Java 8, you can write more concise and readable code using lambda expressions—especially when working with collections and functional interfaces.

In this lesson, you’ll learn:

  • What lambda expressions are
  • Syntax and usage
  • Functional interfaces
  • Method references
  • Real-world examples

Time to embrace functional programming in Java!


⚡ What is a Lambda Expression?

A lambda expression is a short block of code that takes in parameters and returns a value. Think of it as a shortcut for writing anonymous inner classes.

🔹 Basic Syntax:

(parameters) -> expression

Example:

(int a, int b) -> a + b

🔍 Functional Interface

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

Example:

@FunctionalInterface
interface MyFunc {
    void greet();
}

🧪 Using Lambdas with Custom Interface

interface Greeting {
    void sayHello();
}

public class LambdaExample {
    public static void main(String[] args) {
        Greeting g = () -> System.out.println("Hello, Lambda!");
        g.sayHello();
    }
}

➕ Lambdas with Parameters

interface Addable {
    int add(int a, int b);
}

public class Test {
    public static void main(String[] args) {
        Addable sum = (a, b) -> a + b;
        System.out.println(sum.add(10, 20));  // Output: 30
    }
}

✅ Lambdas with Java Built-in Interfaces

Java 8 provides many built-in functional interfaces in java.util.function package:

InterfaceDescription
Predicate<T>Returns boolean
Function<T,R>Takes T, returns R
Consumer<T>Takes T, returns void
Supplier<T>Returns T, takes nothing

🔸 Predicate Example

Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("Lambda"));  // true

🔸 Function Example

Function<String, Integer> getLength = s -> s.length();
System.out.println(getLength.apply("Hello"));  // 5

🔸 Consumer Example

Consumer<String> printer = s -> System.out.println(s);
printer.accept("Printing with Lambda!");

🔸 Supplier Example

Supplier<Double> randomValue = () -> Math.random();
System.out.println(randomValue.get());

🚀 Lambda in Collections

🔸 ForEach with List

List<String> names = Arrays.asList("Amit", "Neha", "Ravi");
names.forEach(name -> System.out.println(name));

🔸 Stream Filter

List<String> names = Arrays.asList("Apple", "Banana", "Avocado");
names.stream()
     .filter(s -> s.startsWith("A"))
     .forEach(System.out::println);  // Apple, Avocado

🔁 Method References (Shorter Lambda)

Instead of:

names.forEach(name -> System.out.println(name));

Use method reference:

names.forEach(System.out::println);

🔐 Benefits of Lambdas

✅ Less boilerplate
✅ Cleaner and readable code
✅ Enables functional programming
✅ Useful with streams and parallelism


🧠 Recap Quiz

What will this code print?

Function<String, String> toUpper = s -> s.toUpperCase();
System.out.println(toUpper.apply("java"));

Answer: JAVA


✅ What You Learned

  • Syntax and usage of lambda expressions
  • Functional interfaces
  • Predicates, Functions, Consumers, Suppliers
  • Method references
  • Using lambdas with collections and streams

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *