温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java8新特性之方法引用的使用方法

发布时间:2021-03-08 13:43:33 来源:亿速云 阅读:127 作者:TREX 栏目:开发技术

这篇文章主要讲解了“Java8新特性之方法引用的使用方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java8新特性之方法引用的使用方法”吧!

一 前言

日常开发中,经常使用到Lambda表达式,例如:

public static void main(String[] args) {
 List<Integer> list = Arrays.asList(1, 5, 10, 4, 2);
 // 打印列表中的每一个数字
 list.forEach((x) -> System.out.println(x));
}

其中(x) -> System.out.println(x)就是使用的Lambda表达式。Lambda表达式可以分为三部分:

  • 左括号:Lambda的形参列表,对应接口的抽象方法的形参列表。

  • 箭头:Lambda的操作符,可以理解为参数列表和Lambda体的分隔符。

  • Lambda体:即对应接口中的抽象方法的实现方法体。

你是否发现,上述例子的Lambda表达式的Lambda体仅仅调用一个已存在的方法,而不做任何其它事。对于这种情况,通过一个方法名字来引用这个已存在的方法会更加清晰。所以,方法引用应运而生,方法引用是一个更加紧凑,易读的Lambda表达式,它是Lambda表达式的另外一种表现形式,方法引用的操作符是双冒号 :: 。

使用了方法引用,上述例子编写如下,变得更加紧凑,易读了。

public static void main(String[] args) {
 List<Integer> list = Arrays.asList(1, 5, 10, 4, 2);
 // 打印列表中的每一个数字
 list.forEach(System.out::println);
}

二 方法引用

方法引用就是通过方法的名字来指向一个方法。它可以使语言的构造更紧凑简洁,减少冗余代码。方法引用的操作符是双冒号 :: 。方法引用有如下几种分类:

类型语法Lambda表达式
静态方法引用类名::静态方法名(args) -> 类名.静态方法名(args)
实例方法引用实例::实例方法名(args) -> 实例.实例方法名(args)
对象方法引用类名::对象方法名(inst,args) -> 类名.对象方法名(args)
构建方法引用类名::new(args) -> new 类名(args)

三 实践

以下例子主要借用学生类来演示,学生类定义如下:

public class Student {

 private String name;
 private Integer age;

 public static int compareByAge(Student s1, Student s2) {
  return s1.age.compareTo(s2.age);
 }

 // 省略属性get/set方法
}

3.1 静态方法引用

现假设有50个学生,存放在一个list列表中,现需要对年龄进行从小到大排序。我们一般会写一个比较器进行排序,如下:

package com.nobody;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Description
 * @Author Mr.nobody
 * @Date 2021/3/7
 * @Version 1.0
 */
public class Test {
 public static void main(String[] args) {

  List<Student> list = new ArrayList<>();
  // 添加元素省略,测试可自行添加
  // 排序
  list.sort(new StudentAgeComparator());
 }
 // 对学生年龄的比较器
 static class StudentAgeComparator implements Comparator<Student> {
  public int compare(Student s1, Student s2) {
   return s1.getAge().compareTo(s2.getAge());
  }
 }
}

我们发现,List的sort方法接受的参数Comparator是一个函数式接口,则可以用Lambda表达式改为如下形式:

list.sort((s1, s2) -> s1.getAge().compareTo(s2.getAge()));

我们又发现,Student类有个静态方法compareByAge,其功能和上述Lambda表达式一样,所以我们可以将以上Lambda表达式改为如下形式:

list.sort((s1, s2) -> Student.compareByAge(s1, s2));

可以看出,最终的Lambda表达式是调用Student类的一个方法,所以,根据静态方法引用规则,可改为如下形式:

list.sort(Student::compareByAge);

3.2 实例方法引用

即引用已经存在的实例的方法。静态方法引用类无需实例化,直接用类名来调用,而实例方法引用是要先实例化对象。

如果将Student类的静态方法compareByAge改为非静态方法,即:

public int compareByAge(Student s1, Student s2) {
 return s1.age.compareTo(s2.age);
}

则可通过如下方式对学生数组进行排序:

list.sort(new Student()::compareByAge);

3.3 对象方法引用

如果Lambda表达式的参数列表中,第一个参数是实例方法的调用者对象,第二个参数是实例方法的参数时,可使用对象方法引用。例如,String的equals()方法:

public static void main(String[] args) {
  BiPredicate<String, String> bp1 = (x, y) -> x.equals(y);
  boolean test1 = bp1.test("Mr.nobody", "Mr.anybody");
  System.out.println(test1);
  
  BiPredicate<String, String> bp2 = String::equals;
  boolean test2 = bp2.test("Mr.nobody", "Mr.anybody");
  System.out.println(test2);
}

再比如,我们在Student类定义如下实例方法,方法中用到了Srudent对象的toString方法。

public class Student {

  private String name;
  private Integer age;

  public static int compareByAge(Student s1, Student s2) {
    return s1.age.compareTo(s2.age);
  }

  // 省略属性get/set方法

  public void whoIam() {
    System.out.println("I am " + this.toString());
  }
  
  @Override
  public String toString() {
    return "Student{" +
        "name='" + name + '\'' +
        ", age=" + age +
        '}';
  }
}
public static void main(String[] args) {

  List<Student> list = new ArrayList<>();
  list.forEach(Student::whoIam);
}

3.4 构造方法引用

注意,引用的构造方法的参数列表要和函数式接口中抽象方法的参数列表保持一致。

public static void main(String[] args) {
  Supplier<Student> studentSupplier1 = () -> new Student();
  Student student1 = studentSupplier1.get();
  
  // 构造方法引用
  Supplier<Student> studentSupplier2 = Student::new;
  Student student2 = studentSupplier2.get();
}

引用数组和引用构造器很像,格式为类型[]::new,等价于lambda 表达式 x -> new int[x]。其中类型可以为基本类型也可以是类。

public static void main(String[] args) {
  
  Function<Integer, Student[]> studentFunction = Student[]::new;
  Student[] students = studentFunction.apply(10);
}

四 总结

方法引用就是通过方法的名字来指向一个方法。它可以使语言的构造更紧凑简洁,减少冗余代码。方法引用的操作符是双冒号 ::

虽然方法引用能带来一些好处,不过也要注意场景的使用,没必要刻意去使用方法引用。因为有时Lambda表达式可能比方法引用更让人理解阅读,也方便必要时修改代码。

感谢各位的阅读,以上就是“Java8新特性之方法引用的使用方法”的内容了,经过本文的学习后,相信大家对Java8新特性之方法引用的使用方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI