ZetCode

Java lambda expression

last modified January 27, 2024

Java lambda expression tutorial shows how to use lambda expressions in Java.

The following is the basic syntax for a lambda expression in Java:

(parameters) -> expression
(parameters) -> { statements; }

Lambda expression allow to create more concise code in Java.

The declaration of the type of the parameter is optional; the compiler can infer the type from the value of the parameter. For a single parameter the parentheses are optional; for multiple parameters, they are required.

The curly braces are optional if there is only one statement in an expression body. Finally, the return keyword is optional if the body has a single expression to return a value; curly braces are required to indicate that the expression returns a value.

com/zetcode/LambdaExpressionEx.java
package com.zetcode;

import java.util.Arrays;

public class LambdaExpressionEx {

    public static void main(String[] args) {

        String[] words = { "kind", "massive", "atom", "car", "blue" };

        Arrays.sort(words, (String s1, String s2) -> (s1.compareTo(s2)));

        System.out.println(Arrays.toString(words));
    }
}

In the example, we define an array of strings. The array is sorted using the Arrays.sort method and a lambda expression.

$ java com/zetcode/LambdaExpressionEx.java
[atom, blue, car, kind, massive]

Interfaces

Lambda expressions are used primarily to define an inline implementation of a functional interface, i.e., an interface with a single method only. Interfaces are abstract types that are used to enforce a contract.

com/zetcode/LambdaExpressionEx.java
package com.zetcode;

interface GreetingService {

    void greet(String message);
}

public class LambdaExpressionEx {

    public static void main(String[] args) {

        GreetingService gs = (String msg) -> {
            System.out.println(msg);
        };

        gs.greet("Good night");
        gs.greet("Hello there");
    }
}

In the example, we create a greeting service with the help of a lambda expression.

interface GreetingService {

    void greet(String message);
}

Interface GreetingService is created. All objects implementing this interface must implement the greet method.

GreetingService gs = (String msg) -> {
    System.out.println(msg);
};

We create an object that implements GreetingService with a lambda expression. The object has a method that prints a message to the console.

gs.greet("Good night");

We call the object's greet method, which prints a give message to the console.

$ java com/zetcode/LambdaExpression.java
Good night
Hello there

Common functional interfaces

There are some common functional interfaces, such as Function, Consumer, or Supplier.

com/zetcode/LambdaExpressionEx.java
package com.zetcode;

import java.util.function.Function;

public class LambdaExpressionEx {

    public static void main(String[] args) {

        Function<Integer, Integer> square = (Integer x) -> x * x;
        System.out.println(square.apply(5));
    }
}

The example uses a lambda expression to compute squares of integers.

Function<Integer, Integer> square = (Integer x) -> x * x;
System.out.println(square.apply(5));

Function is a function that accepts one argument and produces a result. The operation of the lamda expression produces a square of the given integer.

Filtering data

Lambda expression are often used in methods, which expects methods as parameters.

com/zetcode/LambdaExpressionEx.java
package com.zetcode;

import java.util.List;
import java.util.stream.Collectors;

public class LambdaExpressionEx {

    public static void main(String[] args) {

        List<User> persons = List.of(
                new User("Jack", "jack234@gmail.com"),
                new User("Peter", "pete2@post.com"),
                new User("Lucy", "lucy17@gmail.com"),
                new User("Robert", "bob56@post.com"),
                new User("Martin", "mato4@imail.com")
        );

        List<User> result = persons.stream()
                .filter(person -> person.email().matches(".*post\\.com"))
                .collect(Collectors.toList());

        result.forEach(p -> System.out.println(p.name()));
    }
}

record User(String name, String email) {}

The example creates a stream of User objects. It filters those which match a specific regular expression.

List<User> result = persons.stream()
    .filter(person -> person.getEmail().matches(".*post\\.com"))
    .collect(Collectors.toList());

In the filter predicate, we choose emails that match the .*post\\.com pattern. The predicate is a lambda expression.

result.forEach(p -> System.out.println(p.name()));

Also, the method passed to the ForEach is a lambda expression.

Source

Java lambda expressions

In this article we have covered Java lambda expressions.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials.