方法引用與構造方法引用

目錄

方法引用

什么是方法引用

構造方法引用

構造方法引用(也可以稱作構造器引用)

數組構造方法引用


方法引用

什么是方法引用

當要傳遞給?Lambda?體的操作,已經有實現的方法了,可以使用方法引用。

方法引用可以看做是?Lambda?表達式深層次的表達。換句話說,方法引用就是?Lambda?表達式,也就是函數式接口的一個實例,通過方法的名字來指向一個方法,可以認為是?Lambda?表達式的一個語法糖。

要求:實現接口的抽象方法的參數類列和返回值類型,必須與方法引用的方法的參數列表和返回值類型保持一致。

格式:使用操作符?::?將類(或者對象)與方法名分割開來

如下三種主要使用情況:

  • 對象 :: 實例方法名
  • 類 :: 靜態方法名
  • 類 :: 實例方法名

示例

public class Person {private String name;private LocalDate birthday;public Person() {}public Person(String name) {this.name = name;}public Person(String name, LocalDate birthday) {this.name = name;this.birthday = birthday;}public String getName() {return name;}public void setName(String name) {this.name = name;}public LocalDate getBirthday() {return birthday;}public void setBirthday(LocalDate birthday) {this.birthday = birthday;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", birthday=" + birthday +'}';}public static int compareByAge(Person a, Person b) {return a.birthday.compareTo(b.birthday);}
}
public class MethodReferences {//情況一:對象 :: 實例方法//Consumer 中的 void accept(T t) 與 PrintStream 中的 void println(T t)@Testpublic void t1() {//原來的寫法Consumer<String> consumer = new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s);}};consumer.accept("上海市");//lambda 寫法Consumer<String> consumerL = str -> System.out.println(str);consumerL.accept("上海");//方法引用PrintStream out = System.out;Consumer<String> consumerM = out::println;consumerM.accept("shanghai");}//Supplier 中的 T get() 與 Person 中的 String getName()@Testpublic void t2() {Person person = new Person("小威", LocalDate.of(2016, 9, 1));//原來的寫法Supplier<String> supplier = new Supplier<String>() {@Overridepublic String get() {return person.getName();}};System.out.println(supplier.get());//lambda 寫法Supplier<String> supplierL = () -> person.getName();System.out.println(supplierL.get());// 方法引用Supplier<String> supplierM = person::getName;System.out.println(supplierM.get());}
//======================================================================================================================//情況二:類 :: 靜態方法//Comparator 中的 int compare(T t1,T t2) 與 Integer 中的 int compare(T t1,T t2)@Testpublic void t3() {//原來的寫法Comparator<Integer> comparator = new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return Integer.compare(o1, o2);}};System.out.println(comparator.compare(520, 1314));//lambda 寫法Comparator<Integer> comparatorL = (o1, o2) -> Integer.compare(o1, o2);System.out.println(comparatorL.compare(100, 99));// 方法引用Comparator<Integer> comparatorM = Integer::compareTo;System.out.println(comparatorM.compare(123, 321));}//Function 中 R apply(T t) 與 Math 中 Long round(Double d)@Testpublic void t4() {//原來的寫法Function<Double, Long> function = new Function<Double, Long>() {@Overridepublic Long apply(Double aDouble) {return Math.round(aDouble);}};System.out.println(function.apply(13.7));//lambda 寫法Function<Double, Long> functionL = d -> Math.round(d);System.out.println(functionL.apply(13.4));// 方法引用Function<Double, Long> functionM = Math::round;System.out.println(functionM.apply(13.9));}
//======================================================================================================================//情況三:類 :: 實例方法(有難度)//Comparator 中的 int compare(T t1,T t2) 與 String 中的 int t1.compareTo(t2)@Testpublic void t5() {//原來的寫法Comparator<String> comparator = new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return o1.compareTo(o2);}};System.out.println(comparator.compare("abc", "abd"));//lambda 寫法Comparator<String> comparatorL = (o1, o2) -> o1.compareTo(o2);System.out.println(comparatorL.compare("abc", "abd"));// 方法引用Comparator<String> comparatorM = String::compareTo;System.out.println(comparatorM.compare("abd", "abc"));}//BiPredicate 中的 boolean test(T t1,T t2) 與 String 中的 boolean t1.equals(t2)@Testpublic void t6() {//原來的寫法BiPredicate<String, String> biPredicate = new BiPredicate<String, String>() {@Overridepublic boolean test(String s, String s2) {return s.equals(s2);}};System.out.println(biPredicate.test("abc", "abd"));//lambda 寫法BiPredicate<String, String> biPredicateL = (s1, s2) -> s1.equals(s2);System.out.println(biPredicateL.test("abc", "abd"));// 方法引用BiPredicate<String, String> biPredicateM = String::equals;System.out.println(biPredicateM.test("abc", "abd"));}//Function 中的 R apply(T t) 與 Person 中的 String getName()@Testpublic void t7() {Person person = new Person("Vincent", LocalDate.of(1991, 1, 28));//原來的寫法Function<Person, String> function = new Function<Person, String>() {@Overridepublic String apply(Person person) {return person.getName();}};System.out.println(function.apply(person));//lambda 寫法Function<Person, String> functionL = p -> p.getName();System.out.println(functionL.apply(person));// 方法引用Function<Person, String> functionM = Person::getName;System.out.println(functionM.apply(person));}
}

?

構造方法引用

構造方法引用又分構造方法引用和數組構造方法引用。

構造方法引用(也可以稱作構造器引用)

組成語法格式:Class::new

構造函數本質上是靜態方法,只是方法名字比較特殊,使用的是?new?關鍵字

要求:和方法引用類似,函數接口的抽象方法的形參列表和構造器的形參列表一致,且抽象方法的返回值類型即為構造器所屬的類的類型。

示例:

String::new, 等價于?lambda?表達式?() -> new String()

public class ConstructorReferences {//構造器引用//Supplier 中的 T get() 與 Person()@Testpublic void t1() {//原來的寫法Supplier<Person> supplier = new Supplier<Person>() {@Overridepublic Person get() {return new Person();}};System.out.println(supplier.get());//lambda的寫法Supplier<Person> supplierL = () -> new Person();System.out.println(supplierL.get());//構造器引用Supplier<Person> supplierM = Person::new;System.out.println(supplierM.get());}//Function 中的 R apply(T t)@Testpublic void t2() {//原來的寫法Function<String, Person> function = new Function<String, Person>() {@Overridepublic Person apply(String s) {return new Person(s);}};System.out.println(function.apply("小微"));//lambda的寫法Function<String, Person> functionL = s -> new Person(s);System.out.println(functionL.apply("小微"));//構造器引用Function<String, Person> functionM = Person::new;System.out.println(functionM.apply("小微"));}//BiFunction 中的 apply(T t,U u)@Testpublic void t3() {//原來的寫法BiFunction<String, LocalDate, Person> biFunction = new BiFunction<String, LocalDate, Person>() {@Overridepublic Person apply(String s, LocalDate localDate) {return new Person(s, localDate);}};Person person = biFunction.apply("威仔", LocalDate.of(2010, 12, 13));System.out.println(person);//lambda的寫法BiFunction<String, LocalDate, Person> biFunctionL = (s, lD) -> new Person(s, lD);Person personL = biFunctionL.apply("威仔", LocalDate.of(2010, 12, 13));System.out.println(personL);//構造器引用BiFunction<String, LocalDate, Person> biFunctionM = Person::new;Person personM = biFunctionM.apply("威仔", LocalDate.of(2010, 12, 13));System.out.println(personM);}
}

?

數組構造方法引用

組成語法格式:TypeName[]::new

要求:可以把數組看做事一個特殊的類,則寫法與構造器引用一致。

示例:

String[]::new?是一個含有一個參數的構造器引用,這個參數就是數組的長度。等價于?lambda?表達式?x -> new String[x]

public class ConstructorReferences {//數組引用//Function 中的 R apply(T t)@Testpublic void t4() {//原來的寫法Function<Integer, String[]> function = new Function<Integer, String[]>() {@Overridepublic String[] apply(Integer integer) {return new String[integer];}};String[] apply = function.apply(10);System.out.println(Arrays.toString(apply));//lambda的寫法Function<Integer, String[]> functionL = length -> new String[length];String[] applyL = functionL.apply(10);System.out.println(Arrays.toString(applyL));//數組引用Function<Integer, String[]> functionM = String[]::new;String[] applyM = function.apply(10);System.out.println(Arrays.toString(applyM));}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/21150.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/21150.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/21150.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

PHAR反序列化

PHAR PHAR&#xff08;PHP Archive&#xff09;文件是一種歸檔文件格式&#xff0c;phar文件本質上是一種壓縮文件&#xff0c;會以序列化的形式存儲用戶自定義的meta-data。當受影響的文件操作函數調用phar文件時&#xff0c;會自動反序列化meta-data內的內容,這里就是我們反序…

頭歌頁面置換算法第3關:計算LRU算法缺頁率

2 任務:LRU算法 2.1 任務描述 設計LRU頁面置換算法模擬程序:從鍵盤輸入訪問串。計算LRU算法在不同內存頁框數時的缺頁數和缺頁率。要求程序模擬駐留集變化過程,即能模擬頁框裝入與釋放過程。 2.2任務要求 輸入串長度作為總頁框數目,補充程序完成LRU算法。 2.3算法思路 LRU算…

jmeter常用的斷言

包括&#xff08;Contains&#xff09;&#xff1a;響應內容包括需要匹配的內容即代表響應成功&#xff0c;支持正則表達式 匹配&#xff08;Matches&#xff09;&#xff1a;響應內容要完全匹配需要匹配的內容即代表響應成功&#xff0c;大小寫不敏感&#xff0c;支持正則表達…

vue html2canvas生成base64圖片和圖片高度

vue html2canvas生成圖片 exportAsBase64() {const ele document.getElementById(content);html2canvas(ele, {dpi: 96, // 分辨率 scale: 2, // 設置縮放 useCORS: true, // 允許canvas畫布內跨域請求外部鏈接圖片 bgcolor: #ffffff, // 背景顏色 logging: false, // 不…

rust之cargo install cargo-binstall 是什么

cargo-binstall 是什么 官方&#xff1a;https://lib.rs/crates/cargo-binstall Binstall 提供了一種低復雜性的機制來安裝 Rust 二進制文件&#xff0c;作為從源代碼&#xff08;通過 cargo install &#xff09;構建或手動下載軟件包的替代方案。這旨在與現有的 CI 工件和基…

Windows安裝ElasticSearch版本7.17.0

在Windows系統上本地安裝Elasticsearch的詳細步驟如下&#xff1a; 1. 下載Elasticsearch 訪問 Elasticsearch下載頁面。選擇適用于Windows的版本7.17.0&#xff0c;并下載ZIP文件。 2. 解壓文件 下載完成后&#xff0c;找到ZIP文件&#xff08;例如 elasticsearch-7.17.0.…

【算法篇】冒泡排序算法JavaScript版

冒泡排序算法&#xff1a;原理與實現 冒泡排序&#xff08;Bubble Sort&#xff09;是一種簡單的排序算法&#xff0c;它重復地遍歷要排序的數列&#xff0c;一次比較兩個元素&#xff0c;如果它們的順序錯誤就把它們交換過來。遍歷數列的工作是重復地進行直到沒有再需要交換&…

spoon基礎使用-第一個轉換文件

新建一個轉換&#xff0c;文件->新建->轉換&#xff0c;也可以直接ctralN新建。 從右邊主對象樹拖拽一個輸入->表輸入&#xff1b;輸出->文本文檔輸出&#xff1b;也可以直接在搜索框搜素表輸入、文本文檔輸出。 雙擊表輸入新建一個數據庫連接 確定后就可以在S…

【人工智能】第二部分:ChatGPT的架構設計和訓練過程

人不走空 &#x1f308;個人主頁&#xff1a;人不走空 &#x1f496;系列專欄&#xff1a;算法專題 ?詩詞歌賦&#xff1a;斯是陋室&#xff0c;惟吾德馨 目錄 &#x1f308;個人主頁&#xff1a;人不走空 &#x1f496;系列專欄&#xff1a;算法專題 ?詩詞歌…

Java | Leetcode Java題解之第126題單詞接龍II

題目&#xff1a; 題解&#xff1a; class Solution {public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {List<List<String>> res new ArrayList<>();// 因為需要快速判斷擴展出的單詞…

傳輸中的串擾(八)

串擾指的是有害信號從一個線網傳遞到相鄰線網上。通常把噪聲源所在的線網稱為動態線或攻擊線網&#xff0c;而把有噪聲形成的線網稱為靜態線或受害線網。 靜態線上的噪聲電壓的表現與信號電壓完全一樣。一旦在靜態線上產生噪聲電壓&#xff0c;它們就會傳播并在阻抗突變處出現反…

html解決瀏覽器記住密碼輸入框的問題

當瀏覽器記住密碼并自動填充到表單的密碼輸入框時&#xff0c;這通常是瀏覽器為了提供便利而采取的功能。然而&#xff0c;有時這可能不是用戶所期望的&#xff0c;或者你可能希望在某些情況下禁用此功能。 雖然HTML本身并沒有直接提供禁用瀏覽器自動填充密碼輸入框的標準方法…

常見算法(基本查找、二分查找、分塊查找冒泡、選擇、插入、快速排序和遞歸算法)

一、常見算法-01-基本、二分、插值和斐波那契查找 1、基本查找/順序查找 需求1&#xff1a;定義一個方法利用基本查找&#xff0c;查詢某個元素是否存在 數據如下&#xff1a;{131&#xff0c;127&#xff0c;147&#xff0c;81&#xff0c;103&#xff0c;23&#xff0c;7&am…

Leetcode 3170. Lexicographically Minimum String After Removing Stars

Leetcode 3170. Lexicographically Minimum String After Removing Stars 1. 解題思路2. 代碼實現 題目鏈接&#xff1a;3170. Lexicographically Minimum String After Removing Stars 1. 解題思路 這一題的話只需要維護一個有序數列&#xff08;這里我們用堆排來處理&…

C++ C (1152) : 循環賽日程表

文章目錄 一、題目描述二、參考代碼 一、題目描述 二、參考代碼 #include<iostream> #include<vector> #include<cstdlib> using namespace std;void generateSchedule(vector< vector<int> >& table, int numPlayers, int rounds) {// 生…

堆排序-java

這次主要講了堆排序和堆的基本構造&#xff0c;下一期會詳細講述堆的各種基本操作。 文章目錄 前言 一、堆排序 1.題目描述 2.堆 二、算法思路 1.堆的存儲 2. 結點下移down 3.結點上移up 4.堆的基本操作 5.堆的初始化 三、代碼如下 1.代碼如下&#xff1a; 2.讀入數據&#xff…

Harmony os Next——關系型數據庫relationalStore.RdbStore的使用

Harmony os Next——關系型數據庫relationalStore.RdbStore的使用 描述數據庫的使用建表定義表信息創建數據庫表 創建數據庫操作對象增更新查詢刪數據庫的初始化 描述 本文通過存儲一個簡單的用戶信息到數據庫中為例&#xff0c;進行闡述relationalStore.RdbStore數據庫的CRUD…

小公司的軟件開發IT工具箱

目錄 工具鏈困境 難題的解決 達到的效果 資源要求低 工具箱一覽 1、代碼管理工具 2、自動化發版&#xff08;測試&#xff09;工具 3、依賴庫&#xff08;制品包&#xff09;管理 4、鏡像管理 5、授權管理&#xff08;可選&#xff09; 待討論&#xff1a;為什么不是…

LeetCode17電話號碼的字母組合

題目描述 給定一個僅包含數字 2-9 的字符串&#xff0c;返回所有它能表示的字母組合。答案可以按 任意順序 返回。 給出數字到字母的映射如下&#xff08;與電話按鍵相同&#xff09;。注意 1 不對應任何字母。 解析 廣度優先遍歷或者深度優先遍歷兩種方式&#xff0c;廣度優先…

springboot動態切換數據源

1、創建一個springboot項目&#xff0c;導入依賴&#xff08;3.3.0&#xff09; <dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.6.1</version></depe…