Lambda Expressions in Java

Josh - Oct 11 '21 - - Dev Community

This week we are going to go over something I have ran across but didn’t really understand until recently, lambda expressions! Lambda expressions 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
Enter fullscreen mode Exit fullscreen mode

or

(parameter1, parameter2) => {code block}
Enter fullscreen mode Exit fullscreen mode

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()
    {
       System.out.println("Hello");
    }
}

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.
        fobj.abstractFun(5);
    }
}
Enter fullscreen mode Exit fullscreen mode

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>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    Consumer<Integer> method = (n) -> { System.out.println(n); };
    numbers.forEach( method );
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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. I myself am still learning to wrap my head around these concepts. Anyway, I hope you all were able to learn something today. If you have more questions or want to deep dive into this topic check out the links below that I used to write this post. The code examples I pulled are also from there. Have a great week!

Resources:

  1. https://www.w3schools.com/java/java_lambda.asp
  2. https://www.codejava.net/java-core/the-java-language/java-8-lambda-runnable-example
  3. https://www.geeksforgeeks.org/lambda-expressions-java-8/
  4. https://www.developer.com/microsoft/start-using-java-lambda-expressions/
. . . . . . . . . . . . . . . . . . . . .