0
点赞
收藏
分享

微信扫一扫

java8之方法引用简单例子

码农K 2022-01-31 阅读 72
package com.example.demo.java8;

import org.junit.Test;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 方法引用本质上就是lanmda表达式 lanmda表达式是作为函数式接口的实现
 * @FunctionalInterface 函数式接口
 * 方法引用就是函数式接口的实现
 * 要求形参列表和返回值类型要一致
 */
public class TestMethodReference {
    /**
     * 对象::非静态方法 要求形参列表和返回值类型要一致
     * Consumer的 void accept(T t)
     * PrintStream 的 void println(String s)
     */
    @Test
    public void test1(){

        Consumer con1 = str->{System.out.println(str);};
        con1.accept("1123333");

        PrintStream ps = System.out;
        Consumer<String> con2 = ps::println;
        con2.accept("wwwwww");
    }


    /**
     * 要求形参列表和返回值类型要一致
     *
     * Supplier 的 T get();
     * employee 的String getName();
     */
    @Test
    public void test2(){
        Employee employee = new Employee(12,"单点的",25d);

        Supplier<String> s1 = () -> employee.getName();
        System.out.println(s1.get());

        Supplier<String> s2 = employee::getName;
        System.out.println(s2.get());
    }

    /**
     * 类::静态方法  要求形参列表和返回值类型要一致
     * Comparator的int compare(T o1, T o2);
     * Integer的static int compare(int x, int y);
     */
    @Test
    public void test3(){
        Comparator<Integer> com1 = (t1,t2)-> Integer.compare(t1, t2);
        System.out.println(com1.compare(12, 34));

        Comparator<Integer> com2 = Integer::compare;
        System.out.println(com2.compare(78, 68));
    }

    /**
     * Function的R apply(T t);
     * Math 的 static long round(double a)
     */
    @Test
    public void test4(){
        Function<Double,Long> fun1 = d -> Math.round(d);
        System.out.println(fun1.apply(14d));

        Function<Double,Long> fun2 = Math::round;
        System.out.println(fun2.apply(14d));
    }

    /**
     *BiPredicate 的 boolean test(T t, U u);
     *String 的 public boolean equals(Object anObject)
     * 类::非静态方法
     *
     * 参数列表不用一一对应
     *
     * 第一个参数作为方法调用者(t1)
     */
    @Test
    public void test5(){
        BiPredicate<String,String> bp1 = (t1,t2) -> {return t1.equals(t2);};
        System.out.println(bp1.test("11", "222"));

        BiPredicate<String,String> bp2 = String::equals;
        System.out.println(bp2.test("11", "222"));
    }

    /**
     * Function 的 R apply(T t);
     * Employee 的 getName();
     *
     * 第一个参数作为方法调用者(t1)
     *
     */
    @Test
    public void test6(){
        Employee employee = new Employee(15, "我顶顶顶", 25d);

        Function<Employee,String> fun1 = (a) -> a.getName();
        System.out.println(fun1.apply(employee));

        Function<Employee,String> fun2 = Employee::getName;
        System.out.println(fun2.apply(employee));

    }
}

举报

相关推荐

0 条评论