Java Lambda Expressions

Harsh Kulkarni
7 min readMay 30, 2021

--

“A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.”

The lambda expression was introduced first time in Java 8. Its main objective to increase the expressive power of the language. But, before getting into lambdas, we first need to understand functional interfaces.

What is Functional Interface?

“If a Java interface contains one and only one abstract method then it is termed as functional interface. ”

For example, the Runnable interface from package java.lang is a functional interface because it constitutes only one method i.e. run().

Example: Functional Interface in Java

In the above example, the interface displayable has only one abstract method display(). Hence, it is a functional interface.

Here, we have used the annotation @FunctionalInterface. The annotation forces the Java compiler to indicate that the interface is a functional interface. Hence, does not allow to have more than one abstract method. However, it is not compulsory though.

Output: Welcome to Lambda Expressions

Introduction to Lambda Expressions

Lambda expression is an anonymous or unnamed method. The lambda expression does not execute on its own. Instead, it is used to implement a method defined by a functional interface.

Syntax:

Arrow operator (->) is introduced in java through lambda expressions that divides it into two parts i.e. parameters and body.

Lambda Parameters

  1. Zero Parameter

Example: Lambda expression with zero parameter

Output: Shape Triangle with Area : 6

2. One Parameter

Example: Lambda expression with one parameter

Output: Shape Square with Area : 81 sq. units

3. Multiple Parameters

Example: Lambda expression with multiple parameters

Output: Shape Rectangle with Area : 8 sq. units

Lambda Variable Capture

Java Lambda Expression can access variables that are declared outside the lambda function body under certain circumstances.

Example: Code Snippets for Lambda Variable Capture

  1. Local Variable

Output: Grade : B

2. Instance Variable

Output: Obtained Marks : 80

3. Static Variable

output: Total Marks : 100

Method References as Lambdas

“Method reference is an important feature related to lambda expressions, which can let you reuse existing method definitions and pass them just like lambda expressions.”

Syntax for method reference

There are four types of method references:

  1. Method Reference: Static

Example: Code snippet for static method reference

2. Method Reference: Parameter

Example: Code snippet for parameterized method reference

3. Method Reference: Instance

Example: Code snippet for instance method reference

4. Method Reference: Constructor

Example: Code snippet for constructor method reference

Lambda Expression Examples

Example 1: Implementing Runnable using Lambda expression

We were trying to replace anonymous class with lambda expressions, and what could have been the best example of anonymous class than implementing the Runnable interface. Look at the code of implementing runnable prior to Java 8, it’s taking four lines, but with lambda expressions, it’s just taking one line. Here the whole anonymous class is replaced by () -> {} code block.

Output:

Before Java8, too much code for too little to do
In Java8, Lambda expression rocks !!

Example 2: Iterating over List using Lambda expressions

In the below example, I have shown you how to iterate over List using with and without lambda expressions, you can see that now List has a forEach() method, which can iterate through all objects and can apply whatever you ask using lambda code.

output:

Lambdas
Default Method
Stream API
Date and Time API

Example 3: Map method using lambda expressions

In this example we are transforming each element of the costBeforeTax list to its including Value-added Test. We passed a lambda expression x -> x*x to map() method which applies this to all elements of the stream. After that, we use forEach() to print all elements of list.

Output:

112.0
224.0
336.0
448.0
560.0

Example 4: Calculating Maximum, Minimum, Sum and Average of List elements

There is a very useful method called summaryStattics() in stream classes like IntStream, LongStream, and DoubleStream. Which returns an IntSummaryStatistics, LongSummaryStatistics, or DoubleSummaryStatistics describing various summary data about the elements of this stream.

In the following example, we have used this method to calculate the maximum and minimum number in a List. It also has getSum() and getAverage() which can give sum and average of all numbers from List.

Output:

Highest prime number in List : 29
Lowest prime number in List : 2
Sum of all prime numbers : 129
Average of all prime numbers : 12.9

Lambda Expression vs Anonymous Class

Since lambda expression is effectively going to replace Anonymous inner class in new Java code, its important to do a comparative analysis of both of them. One key difference between using Anonymous class and Lambda expression is the use of this keyword.

For anonymous class ‘this’ keyword resolves to anonymous class, whereas for lambda expression ‘this’ keyword resolves to enclose class where lambda is written. Another difference between lambda expression and the anonymous class is in the way these two are compiled. Java compiler compiles lambda expressions and converts them into the private method of the class. It uses invokedynamic byte code instruction from Java 7 to bind this method dynamically.

Applications of Lambda Expressions

  • Simplify testing
  • Implementing listeners and callbacks
  • Maintaining consistency
  • Avoid implementation of new classes

Advantages of Lambda Expressions

  • Code Reduction
  • Readability and consciousness
  • Encouragement of functional programming
  • Code reuse
  • Simplified variable scope

--

--

Responses (6)