Java Lambda Expressions

Java Tutorial

 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)

InterfaceDescriptionMethod
RunnableRepresents a task to run in a threadrun()
Comparator<T>Compares two objectscompare(T o1, T o2)
Consumer<T>Accepts an input, returns nothingaccept(T t)
Supplier<T>Supplies a result, no inputget()
Function<T,R>Takes input, returns resultapply(T t)
Predicate<T>Returns boolean resulttest(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...