Java8六大新特性之四 方法引用和构造器调用

lamdba表达式可以进行简化

下面介绍了6种对lamdba进行简化的方式,也称之为对方法或构造器进行引用。

如果一个lambda表达式代表的只是直接调用这个方法,那么最好还说用名称来调用它,而不是去描述如何调用它。显示地指明方法的名称可以让你的代码可读性更好。

1. 参数类别和返回类型必须与函数式接口中的抽象方法一致
2. 如果参数列表中的第一个参数是实例方法的调用者,第二个参数是实例方法的参数,则可以用ClassName::method

对象::实例方法  -- 方法引用

    //用lambda表达式实现
    Consumer consumer = x -> System.out.println(x);
    consumer.accept("hello world");
    //out实现了println方法
    Consumer consumer1 =System.out::println;
    consumer1.accept("hello word 1");

类名::静态方法  -- 方法引用

    //用lambda表达式实现
    BiFunction<Integer, Integer, Integer> biFun = (x,y) -> Integer.compare(x,y);
    //类名::静态方法
    BiFunction<Integer, Integer, Integer> biFun1 = Integer::compare;
    int result1 = biFun.apply(100,200);
    int result2 = biFun1.apply(100,200);

类名::实例方法  -- 方法引用

    //用lambda表达式实现
    BiFunction<String,String,Boolean> fun1 = (s1,s2)-> s1.equals(s2);
    //类名::实例方法
    BiFunction<String,String,Boolean> fun2 = String::equals;
    fun1.apply("hello","hello");
    fun2.apply("hello","hello");

类名::new          -- 构造器引用

    //用lambda表达式实现
    Supplier<String> sup = ()->new String();
    //构造方法引用 类名::new
    Supplier<String> sup1 = String::new;

类名::new()  -- 构造器引用

    //用lambda表达式实现
    Function<String,Integer> function = x->new Integer(x);
    //类名::new
    Function<String,Integer> function1 = Integer::new;
    function1.apply("100");

String[]:::new     --数组引用

    //用lambda表达式实现
    Function <Integer,String[]> array = x -> new String [x];
    //类型[]::new
    Function <Integer,String[]> array1 = String[]::new;
    array1.apply(5);

所有代码执行结果:

没有报错

1000
10

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/pengweismile/article/details/109559447