Java8新特性之构造器引用、方法引用
生活随笔
收集整理的這篇文章主要介紹了
Java8新特性之构造器引用、方法引用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
構(gòu)造器引用、方法引用
package com.stevenyin.methodref;import org.junit.Test;import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier;/*** @FileName: MethodRef* @Author Steven* @Date: 2021/2/28* 一、方法引用:如果方法已經(jīng)實(shí)現(xiàn),我們可以使用方法引用* (可以理解為方法引用時(shí)lambda表達(dá)式的另外一種表現(xiàn)形式)** 三種引用形式* 1.對(duì)象::實(shí)例方法名* 2.類::靜態(tài)方法名* 3.類::實(shí)例方法名* 注意:* 1.lambda體中的參數(shù)列表和返回值類型與函數(shù)式接口中的參數(shù)列表與返回值類型保持一致!* 2.lambda參數(shù)列表的第一個(gè)參數(shù)是實(shí)例方法的調(diào)用者,而第二個(gè)參數(shù)(或無參)是調(diào)用方法的參數(shù)時(shí),* 可以使用className::method** 二、構(gòu)造器引用* 格式:* className::new* 注意:需要調(diào)用的構(gòu)造器參數(shù)列表與函數(shù)式接口的參數(shù)列表保持一致** 三、數(shù)組引用* 格式:type[]::new*/public class MethodRef<T> {/*** 對(duì)象實(shí)例方法*/@Testpublic void test(){Consumer<T> con=(str)->System.out.println(str);Consumer con1=System.out::println;con1.accept("hello world");PrintStream ps=System.out;Consumer<T> con3=ps::print;}@Testpublic void test2(){List<Integer> list= Arrays.asList(1,2,3,4,5);Supplier<Integer> sup=()->list.size();Supplier<Integer> sup1=list::size;Integer integer = sup1.get();System.out.println(integer);}/*** 類靜態(tài)方法*/@Testpublic void test3(){Function<String,Integer> fun= String::length;Comparator<Integer> comparator=(x,y)->Integer.compare(x, y);Comparator<Integer> comparator1=Integer::compare;int compare = comparator1.compare(2, 3);System.out.println(compare);}/*** 類::實(shí)例方法* lambda的一個(gè)參數(shù)時(shí)實(shí)例方法的調(diào)用者,第二個(gè)參數(shù)(或無參)是實(shí)例方法的參數(shù)時(shí),* 可以使用className::method*/public void test4(){BiPredicate<String,String> predicate=(a,b)->a.equals(b);BiPredicate<String,String> predicate1=String::equals;}/*** lambda的第一個(gè)參數(shù)是實(shí)例方法的調(diào)用者,第二個(gè)參數(shù)(或無參)是調(diào)用方法的參數(shù)時(shí),* 可是使用className::method*/@Testpublic void test5(){Function<String,Integer> fun= String::length;}/*** 構(gòu)造器引用*/@Testpublic void test6(){Supplier<List> supplier= ArrayList::new;System.out.println(supplier.get());}/*** 數(shù)組引用* type[]::new*/@Testpublic void test7(){Function<Integer,String[]> fun=(x)->new String[x];Function<Integer,String[]> fun1=String[]::new;String[] apply = fun1.apply(10);System.out.println(apply.length);} }總結(jié)
以上是生活随笔為你收集整理的Java8新特性之构造器引用、方法引用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决IntelliJ IDEA 2019
- 下一篇: Java字节码技术