Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. Lambda Expressions / (x) -> x * 2

Lambda Expressions / (x) -> x * 2

A lambda expression is a concise notation for expressing a function (method) (Java 8 and later). It lets you pass a method as an argument or implement a functional interface in a single line. Combining it with method references (::) makes the code even more concise.

Syntax

// Basic syntax of a lambda expression.
(parameters) -> expression

// Use a block when the body contains multiple statements.
(parameters) -> {
    // multiple statements
    return value;
}

// Parentheses can be omitted when there is exactly one parameter.
x -> x * 2

// Kinds of method references.
ClassName::staticMethod // e.g., Integer::parseInt
instance::instanceMethod // e.g., str::toUpperCase
ClassName::instanceMethod // e.g., String::length
ClassName::new (constructor reference) // e.g., ArrayList::new

// Specify a sort key with Comparator.comparing().
list.sort(Comparator.comparing(o -> o.getName()));
list.sort(Comparator.comparing(Person::getName));

Common Use Cases

Use caseLambda expression example
Implementing Runnable() -> System.out.println("run")
Sorting a listlist.sort((a, b) -> a.compareTo(b))
Stream filterstream.filter(x -> x > 0)
Stream mapstream.map(x -> x * 2)
forEach operationlist.forEach(s -> System.out.println(s))
Method reference (same as above)list.forEach(System.out::println)
Comparator.comparing()Comparator.comparing(Person::getName)

Sample Code

sample_Lambda.java
import java.util.*;

class Person {
    String name; int age; String favoriteSong;
    Person(String n, int a, String s) { name = n; age = a; favoriteSong = s; }
    String getName() { return name; }
    int getAge() { return age; }
    String getFavoriteSong() { return favoriteSong; }
}

class LambdaExample {
    public static void main(String[] args) {
        // Implement Runnable with a lambda expression.
        Runnable r = () -> System.out.println("Thread started.");
        new Thread(r).start();

        // Sort a list in ascending order.
        List<String> names = new ArrayList<>(List.of("Son Goku", "Vegeta", "Bulma"));
        names.sort((a, b) -> a.compareTo(b));
        System.out.println(names); // Prints [Bulma, Son Goku, Vegeta].

        // Write the same sort using a method reference.
        names.sort(String::compareTo);

        // Sort by a field using Comparator.comparing().
        List<String> words = new ArrayList<>(List.of("Vegeta", "Son Goku", "Krillin", "Bulma"));
        words.sort(Comparator.comparing(String::length));
        System.out.println(words); // Prints [Bulma, Vegeta, Krillin, Son Goku].

        // Write forEach using a method reference.
        List<Integer> nums = List.of(1, 2, 3, 4, 5);
        nums.forEach(System.out::println);

        // Use Comparator.comparing() with a custom class.
        List<Person> people = List.of(new Person("Vegeta", 29, "CHA-LA HEAD-CHA-LA"), new Person("Son Goku", 23, "Makafushigi Adventure!"));
        people.stream()
              .sorted(Comparator.comparing(Person::getAge))
              .forEach(p -> System.out.println(p.getName() + ": " + p.getFavoriteSong()));
    }
}
LambdaExample.java
javac LambdaExample.java
java LambdaExample
# * Thread execution order may vary by environment
Thread started.
[Bulma, Son Goku, Vegeta]
[Bulma, Vegeta, Krillin, Son Goku]
1
2
3
4
5
Son Goku: Makafushigi Adventure!
Vegeta: CHA-LA HEAD-CHA-LA

Note: The timing of thread output may vary depending on the runtime environment.

Overview

A functional interface is an interface that has exactly one abstract method. A lambda expression is used as a concise way to implement such an interface. Compared to anonymous classes, lambda expressions are significantly more concise.

A method reference (::) is an even shorter form of a lambda expression. For example, x -> x.toString() is equivalent to Object::toString. To reference an outer local variable inside a lambda expression, that variable must be "effectively final" (never reassigned).

For the main functional interfaces, see Predicate / Function / Consumer / Supplier.

If you find any errors or copyright issues, please .