• JDK中的方法引用


    若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”,可以理解为方法引用是lambda表达式的另外一种表达形式

    主要有三种语法格式:

    • 对象 :: 实例方法名
    • 类 :: 静态方法名
    • 类 :: 实例方法名

    被引用的方法的参数和返回值必须和要实现的抽象方法的参数和返回值一致

    1.静态方法引用

    //格式:Classname :: staticMethodName  和静态方法调用相比,只是把 . 换为 ::
    String::valueOf   等价于lambda表达式 (s) -> String.valueOf(s)
    Math::pow       等价于lambda表达式  (x, y) -> Math.pow(x, y);

    2.实例对象方法引用

    //格式:instanceReference::methodName
    class ComparisonProvider{
        public int compareByName(Person a, Person b){
            return a.getName().compareTo(b.getName());
        }
        public int compareByAge(Person a, Person b){
            return a.getBirthday().compareTo(b.getBirthday());
        }
    }
    ComparisonProvider myComparisonProvider = new ComparisonProvider();
    Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);

    3.超类上的实例方法引用

    //格式:super::methodName

    //还可以使用this

    4.泛型类和泛型方法引用

    public interface MyFunc<T> {
        int func(T[] als, T v);
    }
    public class MyArrayOps {
         public static <T> int countMatching(T[] vals, T v) {
             int count = 0;
             for (int i = 0; i < vals.length; i++) {
                 if (vals[i] == v) count++;
             }
             return count;
         }
    }
    public class GenericMethodRefDemo {    
        public static <T> int myOp(MyFunc<T> f, T[] vals, T v) {
            return f.func(vals, v);
        }    
        public static void main(String[] args){
            Integer[] vals = {1, 2, 3, 4, 2, 3, 4, 4, 5};
            String[] strs = {"One", "Two", "Three", "Two"};
            int count;
            count=myOp(MyArrayOps::<Integer>countMatching, vals, 4);
            System.out.println("vals contains "+count+" 4s");
            count=myOp(MyArrayOps::<String>countMatching, strs, "Two");
            System.out.println("strs contains "+count+" Twos");
        }
    }

    5.构造器引用

    通过函数式接口实例化类时可以用构造器引用,引用到的是方法参数个数和类型匹配的构造器

    //格式:ClassName :: new,调用默认构造器。
    //lambda方式
    Supplier<Passenger> supplier1 = () -> new Passenger();
    //构造器引用:通过类型推断,引用无参构造器
    Supplier<Passenger> supplier2 = Passenger::new;
    //lambda方式
    BiFunction<String, String, Passenger> function1 = (x, y) -> new Passenger(x, y);
    //构造器引用:通过类型推断,引用有两个String参数的构造器
    BiFunction<String, String, Passenger> function2 = Passenger::new;

    6.数组引用

    //lambda方式

    Function<Integer, String[]> fun1 = (x) -> new String[x];
    String[] strs1 = fun1.apply(10);
    //数组引用
    Function<Integer, String[]> fun2 = String[]::new;
    String[] strs2 = fun2.apply(10);
    一个人有多自律,他就有多强!
  • 相关阅读:
    Python环境搭建
    Python简介
    第一个Java程序
    shiro实战(1)--web
    JDBC释放数据库连接
    IDEA(ideaIU) v2019.2.2详细安装破解教程
    ubuntu通过代理设置update源
    virtualbox FAIL(0x80004005) VirtualBox VT-x is not available (VERR_VMX_NO_VMX)
    Dubbo入门实例
    jsp模板
  • 原文地址:https://www.cnblogs.com/lyang4-09/p/14098976.html
Copyright © 2020-2023  润新知