好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java8新特性之方法引用的实践指南

一 前言

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

?

1

2

3

4

5

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表达式的另外一种表现形式,方法引用的操作符是双冒号 :: 。

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

?

1

2

3

4

5

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)

 

三 实践

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

?

1

2

3

4

5

6

7

8

9

10

11

public class Student {

 

  private String name;

  private Integer age;

 

  public static int compareByAge(Student s1, Student s2) {

   return s1.age测试数据pareTo(s2.age);

  }

 

  // 省略属性get/set方法

}

3.1 静态方法引用

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

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()测试数据pareTo(s2.getAge());

   }

  }

}

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

?

1

list.sort((s1, s2) -> s1.getAge()测试数据pareTo(s2.getAge()));

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

?

1

list.sort((s1, s2) -> Student测试数据pareByAge(s1, s2));

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

?

1

list.sort(Student::compareByAge);

3.2 实例方法引用

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

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

?

1

2

3

public int compareByAge(Student s1, Student s2) {

  return s1.age测试数据pareTo(s2.age);

}

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

?

1

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

3.3 对象方法引用

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

?

1

2

3

4

5

6

7

8

9

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方法。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public class Student {

 

   private String name;

   private Integer age;

 

   public static int compareByAge(Student s1, Student s2) {

     return s1.age测试数据pareTo(s2.age);

   }

 

   // 省略属性get/set方法

 

   public void whoIam() {

     System.out.println( "I am " + this .toString());

   }

  

   @Override

   public String toString() {

     return "Student{" +

         "name='" + name + '\ '' +

         ", age=" + age +

         '}' ;

   }

}

?

1

2

3

4

5

public static void main(String[] args) {

 

   List<Student> list = new ArrayList<>();

   list.forEach(Student::whoIam);

}

3.4 构造方法引用

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

?

1

2

3

4

5

6

7

8

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]。其中类型可以为基本类型也可以是类。

?

1

2

3

4

5

public static void main(String[] args) {

  

   Function<Integer, Student[]> studentFunction = Student[]:: new ;

   Student[] students = studentFunction.apply( 10 );

}

四 总结

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

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

到此这篇关于Java8新特性之方法引用的文章就介绍到这了,更多相关Java8新特性方法引用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestcnblogs测试数据/luciochn/p/14495467.html

查看更多关于Java8新特性之方法引用的实践指南的详细内容...

  阅读:15次