zoukankan      html  css  js  c++  java
  • Java8 方法引用

    方法引用

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

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

    构建方式

    1. 类 :: 静态方法

      Comparator<Integer> com2 = Integer::compare;
      System.out.println(com2.compare(12,3));
    2. 类 :: 非静态方法:你在引用一个对象的方法,譬如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"));
    3. 对象 :: 非静态方法

      PrintStream ps = System.out;
      Consumer<String> con2 = ps::println;

    构造函数引用

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

    1. Supplier中的T get()

      Supplier<Employee> sup = () -> new Employee();
      System.out.println("*******************");

      Supplier<Employee>  sup1 = () -> new Employee();
      System.out.println(sup1.get());

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

      Supplier<Employee>  sup2 = Employee :: new;
      System.out.println(sup2.get());
    2. Function中的R apply(T t)

      Function<Integer,Employee> func1 = id -> new Employee(id);
      Employee employee = func1.apply(1001);
      System.out.println(employee);

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

      Function<Integer,Employee> func2 = Employee :: new;
      Employee employee1 = func2.apply(1002);
      System.out.println(employee1);
    3. BiFunction中的R apply(T t,U u)

      BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(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"));
    4. 数组引用

      Function<Integer,String[]> func1 = length -> new String[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));
    莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。
  • 相关阅读:
    PXE无人自动安装系统 大风起
    httpd基于域名的虚拟主机的简单介绍 大风起
    tomcat优化方案 大风起
    tomcat架构 大风起
    Tomcat优化2 大风起
    NET 2.0学习
    删除VS2005历史记录
    在淘宝上建了个小店,在自己的小窝里宣传一下
    微软提供的ASP.NET 2.0空间,你还不赶紧去注册!!呵呵
    DataGridView.BackGroundImage你用过吗?
  • 原文地址:https://www.cnblogs.com/GGuoLiang/p/13604547.html
Copyright © 2011-2022 走看看