Java8新特性-方法引用(第二天)

概念

方法引用可以被看作仅仅调用特定方法的Lambda的一种快捷写法。实质就是让你根据已有的方法实现来创建Lambda表达式。

语法

构造器引用: 它的语法是Class::new,或者更一般的Class< T >::new 实例如下:

Supplier<Apple> c1 = () -> new Apple();
Apple a1 = c1.get();
可写作:
Supplier<Apple> c1 = Apple::new;
Apple a1 = c1.get();

Function<Integer, Apple> c2 = (weight) -> new Apple(weight);
Apple a2 = c2.apply(110);
可写作:
Function<Integer, Apple> c2 = Apple::new;
Apple a2 = c2.apply(110);

ps: Supplier接口的get方法作用是不接收参数,返回一个T类型的对象
Function<T,R>接口的apply方法作用是接收一个T参数,返回R类型的对象


看一个例子:

        List<Integer> weights = Arrays.asList(7, 3, 4, 10);
        List<Apple> apples = map(weights, Apple::new); //将构造函数引用传递给map方法,构造函数里面赋值了
        public static List<Apple> map(List<Integer> list,
                Function<Integer, Apple> f){
            List<Apple> result = new ArrayList<>();
            for(Integer e: list){
                result.add(f.apply(e));
        }
        return result;
}

指向静态方法引用: 它的语法是Class::static_method 实例如下:

(String s) -> Integer.parseInt(s) 可写作: Integer::parseInt

指向任意类型实例方法的方法引用: 它的语法是Class::method 实例如下:

(String s)-> s.toUpperCase() 可写作  String::toUpperCase

指向现有对象的实例方法的方法引用: 它的语法是instance::method 实例如下:

已存在的一个外部对象temp,有个方法instanceMethod
(args) -> temp.instanceMethod(args) 可写作 temp::instanceMethod(args)

3和4的区别是,s是Lambda中的一个参数,而temp是外部对象的引用。

posted @ 2019-09-06 16:43  cilieyes  阅读(161)  评论(0编辑  收藏  举报