Java8新特性之构造器引用、方法引用
生活随笔
收集整理的這篇文章主要介紹了
Java8新特性之构造器引用、方法引用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
構造器引用、方法引用
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* 一、方法引用:如果方法已經實現,我們可以使用方法引用* (可以理解為方法引用時lambda表達式的另外一種表現形式)** 三種引用形式* 1.對象::實例方法名* 2.類::靜態方法名* 3.類::實例方法名* 注意:* 1.lambda體中的參數列表和返回值類型與函數式接口中的參數列表與返回值類型保持一致!* 2.lambda參數列表的第一個參數是實例方法的調用者,而第二個參數(或無參)是調用方法的參數時,* 可以使用className::method** 二、構造器引用* 格式:* className::new* 注意:需要調用的構造器參數列表與函數式接口的參數列表保持一致** 三、數組引用* 格式:type[]::new*/public class MethodRef<T> {/*** 對象實例方法*/@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);}/*** 類靜態方法*/@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);}/*** 類::實例方法* lambda的一個參數時實例方法的調用者,第二個參數(或無參)是實例方法的參數時,* 可以使用className::method*/public void test4(){BiPredicate<String,String> predicate=(a,b)->a.equals(b);BiPredicate<String,String> predicate1=String::equals;}/*** lambda的第一個參數是實例方法的調用者,第二個參數(或無參)是調用方法的參數時,* 可是使用className::method*/@Testpublic void test5(){Function<String,Integer> fun= String::length;}/*** 構造器引用*/@Testpublic void test6(){Supplier<List> supplier= ArrayList::new;System.out.println(supplier.get());}/*** 數組引用* 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);} }總結
以上是生活随笔為你收集整理的Java8新特性之构造器引用、方法引用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决IntelliJ IDEA 2019
- 下一篇: Java字节码技术