Java Lambda Expressions

Gökhan Kanber
2 min readFeb 14, 2021
Milky Way

This article is a part of the Java Programming Language article series.

Lambda Expressions

  • Treat functionality as method argument, or code as data
  • For anonymous class implementations
  • Looks a lot like a method declaration
  • Consider as anonymous methods: methods without a name

Syntax of Lambda Expressions

A comma-separated list of parameters enclosed in parenthese

  • Omit the data type of the parameters
  • Omit the parentheses if there is only one parameter

The arrow token: ->

A body, which consists of a single expression or a statement block

  • For a single expression, the Java runtime evaluates the expression and then returns its value
  • A return statement can be used
  • A return statement is not an expression, enclose statements in braces {}
  • Do not have to enclose a void method invocation in braces

Functional Interface

  • An interface that contains only one abstract method
  • May contain one or more default methods or static methods
  • Reduces the amount of code
  • Standard functional interfaces: the java.util.function package

Approaches from Naive to Lambda Expressions

  • Approach 1: A method that search one characteristic
  • Approach 2: Using an anonymous class
  • Approach 3: Using a lambda expression
  • Approach 4: Using standard functional interfaces with lambda expressions
  • Approach 5: Using lambda expressions with Consumer
  • Approach 6: Using lambda expressions with Function
  • Approach 7: Using generics
  • Approach 8: Use Aggregate Operations That Accept Lambda Expressions as Parameters

Approach 1: A method that search one characteristic

Approach 2: Using an anonymous class

Approach 3: Using a lambda expression

Approach 4: Using standard functional interfaces with lambda expressions

Approach 5: Using lambda expressions with Consumer

Approach 6: Using lambda expressions with Function

Approach 7: Using generics

Approach 8: Use Aggregate Operations That Accept Lambda Expressions as Parameters

Mapping from processElements Action to Aggregate Operation
Mapping from processElements Action to Aggregate Operation

Anonymous Methods

--

--