Lambda Expressions in Java

📘 Java 👁 46 views 📅 Dec 01, 2025
⏱ Estimated reading time: 2 min

Lambda expressions were introduced in Java 8 to provide a concise way to represent anonymous functions. They enable functional programming in Java and are mainly used with functional interfaces.


1. What is a Lambda Expression?

  • A lambda expression allows you to pass functionality as an argument to methods.

  • Syntax:

(parameters) -> expression

or

(parameters) -> { statements; }
  • Eliminates the need for anonymous inner classes.


2. Functional Interface

  • A functional interface is an interface with exactly one abstract method.

  • Examples: Runnable, Comparator, ActionListener

  • Can include default and static methods.

@FunctionalInterface interface Drawable { void draw(); }

3. Examples of Lambda Expressions

Example 1: Runnable

public class Test { public static void main(String[] args) { Runnable r = () -> System.out.println("Thread is running..."); new Thread(r).start(); } }

Output:

Thread is running...

Example 2: Comparator with Lambda

import java.util.Arrays; import java.util.Comparator; public class Test { public static void main(String[] args) { String[] fruits = {"Apple", "Orange", "Banana"}; Arrays.sort(fruits, (s1, s2) -> s1.compareTo(s2)); for (String fruit : fruits) { System.out.println(fruit); } } }

Output:

Apple Banana Orange

Example 3: Custom Functional Interface

@FunctionalInterface interface MathOperation { int operation(int a, int b); } public class Test { public static void main(String[] args) { MathOperation add = (a, b) -> a + b; MathOperation multiply = (a, b) -> a * b; System.out.println("Addition: " + add.operation(5, 3)); System.out.println("Multiplication: " + multiply.operation(5, 3)); } }

Output:

Addition: 8 Multiplication: 15

4. Key Features of Lambda Expressions

  • Concise syntax → No need for anonymous classes

  • Type inference → Compiler infers parameter types

  • Can access final or effectively final variables from the enclosing scope

  • Used extensively in Streams API for operations like map, filter, and forEach


5. Advantages

  • Reduces boilerplate code

  • Enables functional programming style

  • Enhances readability and maintainability

  • Works seamlessly with Collections and Streams API


6. Key Points

  • Lambda expressions are stateless; no instance variables can be used unless final or effectively final.

  • Can only be used where a functional interface is expected.

  • Helps in event handling, multithreading, and data processing.


7. Conclusion

Lambda expressions make Java more expressive, concise, and functional. They are a cornerstone of modern Java programming, enabling cleaner code, functional programming paradigms, and easier handling of collections and streams.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes