Java8新特性——方法、构造器、数组引用详解

/*
* 方法引用:若lambda体中的内容有方法已进化实现了,我们可以使用"方法引用"
*        (可以理解为方法引用是lambda表达式的另外一种表现形式)
* 主要有三种语法格式:
*   对象::实例方法名
*   类::静态方法名
*   类::实例方法名
*
* 注意:
*    ①、Lambda体中调用方法的参数列表以返回值类型,
*       要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
*    ②、若lambda参数列表中第一个参数是实例方法的调用者,
*        而第二个参数是实例方法的参数时,可以用ClassName::method
* 构造器引用
*    格式:ClassName::new
*    注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致!
* 数组引用:
*     Type[]::new;
* */
public class MethodAndConstructor {
//    对象::实例方法名
    @Test
    public void test1(){
        PrintStream ps1 = System.out;
        Consumer<String> con = (x) -> ps1.println(x);
        Consumer<String> con1 = ps1::println;
        con.accept("hdfs,commom,yarn,maprreduce");
        con1.accept("hdfs,commom,yarn,maprreduce");
    }
    @Test
    public void test2(){
        Employee emp = new Employee();
        Supplier<String> sup = () -> emp.getName();
        String str = sup.get();
        System.out.println(str);

        Supplier<Integer> sup2 = emp::getAge;
        Integer num = sup2.get();
        System.out.println(num);
    }
//    类::静态方法名
    @Test
    public void test3(){
        Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
        Comparator<Integer> com1 = Integer::compare;
    }
//     类::实例方法名
    @Test
    public void test4(){
        BiPredicate<String,String> bp = (x,y) -> x.equals(y);
        BiPredicate<String,String> bp1 = String::equals;
    }
//    构造器引用
    @Test
    public void test5(){
        Supplier<Employee> sup = () -> new Employee();
//       构造器引用方式
        Supplier<Employee> sup2 = Employee::new;
    }
    @Test
    public void test6(){
        Function<Integer,Employee> fun = (x) -> new Employee(x);
        Function<Integer,Employee> fun2 = Employee::new;
        Employee emp = fun2.apply(101);
        System.out.println(emp);

        BiFunction<String,Integer,Employee> bf = Employee::new;
    }
//  数组引用
    @Test
    public void test7(){
        Function<Integer,String[]> fun = (x) -> new String[x];
        String [] str = fun.apply(10);
        System.out.println(str.length);

        Function<Integer,String[]> fun2 = String[]::new;;
        String[] str1 = fun2.apply(20);
        System.out.println(str1.length);
    }
}
发布了88 篇原创文章 · 获赞 383 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/weixin_42047611/article/details/81516457
今日推荐