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> {
    
    

    /**
     * 对象实例方法
     */
    @Test
    public 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;

    }

    @Test
    public 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);
    }

    /**
     * 类静态方法
     */
    @Test
    public 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
     */
    @Test
    public void test5(){
    
    
        Function<String,Integer> fun= String::length;
    }

    /**
     * 构造器引用
     */
    @Test
    public void test6(){
    
    
        Supplier<List> supplier= ArrayList::new;
        System.out.println(supplier.get());
    }

    /**
     * 数组引用
     * type[]::new
     */
    @Test
    public 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);
    }
}

猜你喜欢

转载自blog.csdn.net/SuperstarSteven/article/details/114236558
今日推荐