by BehindJava

Lambda Expressions in Java

Home » java » Lambda Expressions in Java

In this tutorial we are going to learn about Lambda expressions that are Java dipping its toes into functional programming. It takes parameters and applies it to an expression or code block. Below is a basic example of the syntax:

(parameter1, parameter2) => expression


(parameter1, parameter2) => {code block}

Lambda expressions are extremely limited and must immediately return a value if it isn’t void. They can’t use keywords such as if or for to maintain simplicity. If more lines of code are needed then you can use a code block instead.

Now when implementing lambdas you can’t only use the expression. Lambdas are implementations of functional interfaces. A functional interface is an interface that only has one abstract method. The benefits of lambdas are that they allow you to implement the method without having to implement the interface’s class and instantiate an object. An example of this is below:

interface FuncInterface
    // An abstract function
    void abstractFun(int x);

    // A non-abstract (or default) function
    default void normalFun()

class Test
    public static void main(String args[])
        // lambda expression to implement above
        // functional interface. This interface
        // by default implements abstractFun()
        FuncInterface fobj = (int x)->System.out.println(2*x);

        // This calls above lambda expression and prints 10.

Lambda expressions are often used as parameters to a function. To increase readability you can also store lambda expressions in a variable as long as the type is an interface that only has one method, the same number of parameters, and the same return type.

import java.util.ArrayList;
import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    Consumer<Integer> method = (n) -> { System.out.println(n); };
    numbers.forEach( method );

A common use for lambdas are creating threads. Here is an example of implementing a Runnable object with a lambda code block for the thread to execute.

// Lambda Runnable
Runnable task2 = () -> { System.out.println("Task #2 is running"); };

// start the thread
new Thread(task2).start();

Most of us as beginners have been taught to program using OOP concepts so it can be a bit jarring to use a different paradigm like functional programming. Have a great week!