美文网首页
Java8 方法引用

Java8 方法引用

作者: GGuoLiang | 来源:发表于2020-09-02 22:02 被阅读0次

    方法引用

    方法引用可以被看作仅仅调用特定方法的Lambda的一种快捷写法。如果一个Lambda代表的只是“直接调用这个方法”,那最好还是用名称来调用它,而不是去描述如何调用它。

    当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用

    构建方式

    类 :: 静态方法

    Comparator<Integer>com2=Integer::compare;

    System.out.println(com2.compare(12,3));

    类 :: 非静态方法:你在引用一个对象的方法,譬如String::length,而这个对象是Lambda表达式的一个参数。举个例子,Lambda表达式(String s) -> s.toUppeCase()可以重写成String::toUpperCase

    Comparator<String>com1=(s1,s2)->s1.compareTo(s2);

    System.out.println(com1.compare("abc","abd"));

    System.out.println("*******************");

    Comparator<String>com2=String::compareTo;

    System.out.println(com2.compare("abd","abm"));

    对象 :: 非静态方法

    PrintStreamps=System.out;

    Consumer<String>con2=ps::println;

    Supplier<Employee>sup2=Employee::new;

    System.out.println(sup2.get());

    Supplier中的T get()

    Supplier<Employee>sup=()->newEmployee();

    System.out.println("*******************");

    Supplier<Employee>sup1=()->newEmployee();

    System.out.println(sup1.get());

    System.out.println("*******************");

    Supplier<Employee>sup2=Employee::new;

    System.out.println(sup2.get());

    Function中的R apply(T t)

    Function<Integer,Employee>func1=id->newEmployee(id);

    Employeeemployee=func1.apply(1001);

    System.out.println(employee);

    System.out.println("*******************");

    Function<Integer,Employee>func2=Employee::new;

    Employeeemployee1=func2.apply(1002);

    System.out.println(employee1);

    BiFunction中的R apply(T t,U u)

    BiFunction<Integer,String,Employee>func1=(id,name)->newEmployee(id,name);

    System.out.println(func1.apply(1001,"Tom"));

    System.out.println("*******************");

    BiFunction<Integer,String,Employee>func2=Employee::new;

    System.out.println(func2.apply(1002,"Tom"));

    数组引用

    Function<Integer,String[]>func1=length->newString[length];

    String[]arr1=func1.apply(5);

    System.out.println(Arrays.toString(arr1));

    System.out.println("*******************");

    Function<Integer,String[]>func2=String[] ::new;

    String[]arr2=func2.apply(10);

    System.out.println(Arrays.toString(arr2));

    对于一个现有构造函数,你可以利用它的名称和关键字new来创建它的一个引用:ClassName::new。它的功能与指向静态方法的引用类似。

    构造函数引用

    相关文章

      网友评论

          本文标题:Java8 方法引用

          本文链接:https://www.haomeiwen.com/subject/djdgsktx.html