Java Lambda Expressions

⚡ Java Lambda Expressions

Lambda expressions in Java provide a concise way to represent an anonymous function (a function without a name).
Introduced in Java 8, they simplify functional programming and reduce boilerplate code.

  • Often used with Functional Interfaces (interfaces with a single abstract method)

  • Improves readability, especially in Collections and Streams


✅ 1. Syntax


  • Parameters – inputs to the lambda

  • Arrow token -> separates parameters from the body

  • Expression or block – body of the lambda


🔹 2. Example: Simple Lambda Expression


 

  • (name) -> System.out.println("Hello, " + name + "!") is the lambda expression


🔹 3. Lambda with No Parameters


 

  • Empty parentheses () used when no parameters


🔹 4. Lambda with Multiple Parameters


 

  • Can include multiple statements using {}:


🔹 5. Lambda with Return Values

  • For single expressions, return keyword is optional.

  • For multiple statements, return is required:


🔹 6. Using Lambdas with Collections


 

  • Lambda expressions are commonly used with forEach, sort, and Streams API


🔹 7. Functional Interfaces (Predefined)

Interface Description Method
Runnable Represents a task to run in a thread run()
Comparator<T> Compares two objects compare(T o1, T o2)
Consumer<T> Accepts an input, returns nothing accept(T t)
Supplier<T> Supplies a result, no input get()
Function<T,R> Takes input, returns result apply(T t)
Predicate<T> Returns boolean result test(T t)

🔹 8. Example: Using Predicate


 

  • Simplifies code by using predefined functional interfaces


✅ Summary

  • Lambda Expression = concise representation of anonymous function

  • Introduced in Java 8, works with functional interfaces

  • Reduces boilerplate for collections, threads, and event handling

  • Syntax: (parameters) -> expression/block

You may also like...