Lambda Expression in JAVA

A lambda expression is a short block of code which takes in parameters and returns a value. It’s a way to write anonymous functions (functions without names).

Java introduced lambda expressions in Java 8 to enable functional programming.

Why Use Lambda Expressions?

Lambda expressions aren’t strictly necessary (Java worked fine without them before Java 8), but they were added to:

  • Write cleaner, shorter code (especially for interfaces with a single method)
  • Replace anonymous inner classes
  • Make working with collections easier (e.g., with forEach, filter, etc.)
  • Support Functional Programming. Java 8 introduced functional programming concepts like:
    • Streams
    • Method references
    • map, filter, reduce, These all work great with lambdas.
  • Better Use of Multi-Core Processors. Functional programming + lambda expressions = easier parallel processing using Streams.

Lambda Expression Syntax

(parameters) -> { body }

(parameter1, parameter1) -> { Code block }