在 Java 中,方法引用(Method Reference)是一種簡化 Lambda 表達式的寫法。它允許你引用已經存在的方法或構造函數。方法引用主要有四種類型:
下面是如何使用方法引用的示例:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class MethodReferenceExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// 靜態方法引用
List<String> lowerCaseNames = names.stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
System.out.println(lowerCaseNames); // 輸出: [alice, bob, charlie]
// 特定對象的實例方法引用
Person person = new Person("John");
List<String> namesWithInitials = names.stream()
.map(name -> person.getName().concat(". ").concat(name))
.collect(Collectors.toList());
System.out.println(namesWithInitials); // 輸出: [John. Alice, John. Bob, John. Charlie]
// 任意對象的實例方法引用
List<Integer> lengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths); // 輸出: [5, 3, 6]
// 構造方法引用
List<Person> people = names.stream()
.map(Person::new)
.collect(Collectors.toList());
System.out.println(people); // 輸出: [Person{name='Alice'}, Person{name='Bob'}, Person{name='Charlie'}]
}
}
在這個示例中,我們使用了不同的方法引用來處理一個字符串列表。這些方法引用分別引用了 String
類的靜態方法 toLowerCase()
、Person
類的實例方法 getName()
、任意對象的實例方法 length()
以及 Person
類的構造方法。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。