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));
    莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。
  • 相关阅读:
    罗尔定理、微分中值定理、广义微分中值定理
    高等数学和数学分析教材推荐及其学习方法浅谈
    音视频下载插件 安装及使用
    win10台式机rtl8188eu(FW 150 UM V2.0)无线网卡无法连接wifi(无法连接到这个网络)
    django模板中的extends和include使用方法
    wordpress中文目录出现“有点尴尬诶!该页无法显示"
    wordpress迁移后登陆时出现Forbidden You don’t have permission to access /wp-login.php on this server
    centos设置开机自启动脚本
    hexo的jacman主题设置语言为英文后偶尔出现中文
    安卓QQ聊天记录导出、备份完全攻略
  • 原文地址:https://www.cnblogs.com/GGuoLiang/p/13604547.html
Copyright © 2011-2022 走看看