Chuyển đến nội dung chính
eLearner.app
Mô-đun 7 · Bài học 1 trong tổng số 213/14 trong khóa học~12 min
Bài học theo mô-đun (1/2)

Biểu thức Lambda

Starting from Java 8, functional programming is supported via Lambda Expressions. A lambda expression is essentially an anonymous method (a function without a name) that can be passed as an argument to methods or stored in variables.

Functional Interfaces

A lambda expression can only be used where a Functional Interface is required. A functional interface is an interface that declares exactly one abstract method. Java marks these interfaces with the optional @FunctionalInterface annotation.

Example of a user-defined functional interface:

Code
@FunctionalInterface
interface MathOperation {
    int operate(int a, int b);
}

Before Java 8, you would have to define an anonymous inner class. With lambdas, the syntax is simplified to:

Code
MathOperation addition = (a, b) -> a + b;
int result = addition.operate(5, 3); // Returns 8

Structure of Lambda Expressions

The basic syntax of a lambda is:

Code
(parameters) -> { body }
  • Without parameters: () -> System.out.println("Hello")
  • Single parameter: x -> x * 2 (parentheses can be omitted)
  • Multiple parameters: (x, y) -> x + y
  • Multi-line body: if the body contains multiple statements, braces {} and an explicit return statement are required.
Code
MathOperation detailedAddition = (a, b) -> {
    System.out.println("Adding...");
    return a + b;
};

Standard Functional Interfaces in Java

The java.util.function package provides several built-in functional interfaces:

  • Predicate<T>: accepts an argument of type T and returns a boolean (test(T t) method).
  • Consumer<T>: accepts an argument of type T and performs an operation without returning a result (accept(T t) method).
  • Function<T, R>: accepts an argument T and returns a result R (apply(T t) method).
  • Supplier<T>: accepts no arguments and returns a value of type T (get() method).

Try it yourself

tập thể dục#java.m7.l1.e1
Nỗ lực: 0Đang tải…

Complete the code by instantiating the Calculator interface using a lambda expression that adds two integers. Then, invoke the calculate method passing 5 and 3, and print the result.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Declare `Calculator adder = (a, b) -> a + b;` and then invoke `adder.calculate(5, 3)` inside the print call.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#java.m7.l1.e2
Nỗ lực: 0Đang tải…

Create an instance of the standard functional interface Predicate<String> named isLong using a lambda expression that checks if the string length is greater than 5 characters. Then print the test result for 'hello world'.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

The lambda for a `Predicate<String>` takes a parameter `s` and returns `s.length() > 5` as a boolean condition.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#java.m7.l1.e3
Nỗ lực: 0Đang tải…

Sort the list of strings names alphabetically by invoking the sort() method on it and passing a lambda expression that implements Comparator (taking two strings s1, s2 and comparing them using compareTo).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use `names.sort((s1, s2) -> s1.compareTo(s2));` to sort the list in place.

Giải pháp khả dụng sau 3 lần thử