Method reference (::) là cú pháp rút gọn lambda khi lambda chỉ gọi 1 method và truyền argument y nguyên.
| Loại | Cú pháp | Tương đương | Ví dụ |
|---|---|---|---|
| Static | Class::staticMethod | x -> Class.staticMethod(x) | Integer::parseInt |
| Bound instance | obj::method | x -> obj.method(x) | System.out::println |
| Unbound instance | Class::method | (obj, x) -> obj.method(x) | String::toUpperCase |
| Constructor | Class::new | x -> new Class(x) | ArrayList::new |
java
list.stream().map(Integer::parseInt).toList(); // static
names.forEach(System.out::println); // bound instance
names.stream().map(String::toUpperCase).toList(); // unbound instance
Supplier<List<String>> factory = ArrayList::new; // constructorNên dùng khi lambda chỉ wrap 1 method, không có logic thêm. Giữ lambda khi có xử lý thêm (s -> s.trim().toLowerCase()).
Method reference không nhanh hơn lambda — chỉ là đường cú pháp. Tiêu chí duy nhất: readability.
A method reference (::) shortens a lambda when the lambda just calls one method and forwards arguments unchanged.
| Kind | Syntax | Equivalent | Example |
|---|---|---|---|
| Static | Class::staticMethod | x -> Class.staticMethod(x) | Integer::parseInt |
| Bound instance | obj::method | x -> obj.method(x) | System.out::println |
| Unbound instance | Class::method | (obj, x) -> obj.method(x) | String::toUpperCase |
| Constructor | Class::new | x -> new Class(x) | ArrayList::new |
java
list.stream().map(Integer::parseInt).toList(); // static
names.forEach(System.out::println); // bound instance
names.stream().map(String::toUpperCase).toList(); // unbound instance
Supplier<List<String>> factory = ArrayList::new; // constructorPrefer method references when the lambda only wraps one method. Keep a lambda when there is extra logic (s -> s.trim().toLowerCase()).
Method references are not faster than lambdas — pure syntactic sugar. Only criterion: readability.