溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java Method Reference 如何使用

發布時間:2025-02-09 07:48:07 來源:億速云 閱讀:119 作者:小樊 欄目:編程語言

在 Java 中,方法引用(Method Reference)是一種簡化 Lambda 表達式的寫法。它允許你引用已經存在的方法或構造函數。方法引用主要有四種類型:

  1. 靜態方法引用(Static Method Reference):用于引用類的靜態方法。
  2. 特定對象的實例方法引用(Instance Method Reference):用于引用特定對象的實例方法。
  3. 任意對象的實例方法引用(Any Object’s Instance Method Reference):用于引用任意對象的實例方法。
  4. 構造方法引用(Constructor Reference):用于引用類的構造方法。

下面是如何使用方法引用的示例:

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 類的構造方法。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女