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

import java.util.*;

// 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("Charlie", "Alice", "Bob"));
names.sort((a, b) -> a.compareTo(b));
System.out.println(names); // Prints [Alice, Bob, Charlie].

// 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("banana", "fig", "apple", "kiwi"));
words.sort(Comparator.comparing(String::length)); // Sort by string length.
System.out.println(words); // Prints [fig, kiwi, apple, banana].

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

// Use Comparator.comparing() with a custom class.
class Person {
    String name; int age;
    Person(String n, int a) { name = n; age = a; }
    String getName() { return name; }
    int getAge() { return age; }
}
List<Person> people = List.of(new Person("Bob", 30), new Person("Alice", 25));
people.stream()
      .sorted(Comparator.comparing(Person::getAge))
      .forEach(p -> System.out.println(p.getName())); // Prints "Alice" then "Bob".

Overview

A lambda expression is used as an implementation of a functional interface (an interface that has exactly one abstract method). 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 .