πŸ”Ή What is a Lambda Expression?

AΒ Lambda Expression in Java is a short block of code that takes in parameters and returns a value, used primarily to implement functional interfaces.

βœ… Think of it as a way to write anonymous functions more cleanly.


πŸ“Œ Syntax of Lambda

(parameter1, parameter2) -> { body }

Examples:

// 1. No parameter
() -> System.out.println("Hello Lambda");

// 2. One parameter, no return
name -> System.out.println("Hi " + name);

// 3. Two parameters with return
(a, b) -> a + b


🎯 Functional Interface Reminder

A Functional Interface has only one abstract method.

Example:


@FunctionalInterface
interface MyInterface {
Β  Β  void sayHello();
}

You can use a lambda to implement it:

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

βœ… Real-World Usage

πŸ”Ή 1. Using Lambda with Threads

new Thread(() -> System.out.println("Running thread")).start();

πŸ”Ή 2. Using Lambda with Collections

List<String> names = Arrays.asList("Aftab", "Nitin", "Ravi");

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


πŸ”Ή 3. Comparator Example

Collections.sort(names, (s1, s2) -> s1.compareTo(s2));

πŸ“¦ Common Functional Interfaces in java.util.function

Interface Method Signature Example Usage
Predicate<T> boolean test(T t) Filtering lists
Function<T,R> R apply(T t) Mapping values
Consumer<T> void accept(T t) Printing, logging
Supplier<T> T get() Supplying default values

πŸš€ Benefits of Lambda Expressions

  • More concise and readable code
  • Enables functional programming
  • Reduces boilerplate (e.g., anonymous inner classes)
  • Great for stream and collection APIs

🧠 Summary

Concept Example
Basic Syntax (a, b) -> a + b
Functional Interface One method interface (e.g., Runnable)
Use Case Collections, threads, event handling
Advantage Concise, elegant, modern code

Β 

Β 

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.