JDK8-Lambda表达式

这是我参与11月更文挑战的第19天,活动详情查看:2021最后一次更文挑战

欢迎关注公众号OpenCoder,来和我做朋友吧~❤😘😁🐱‍🐉👀

Lambda表达式

概述

官网对lambda表达式的描述

官网:docs.oracle.com/javase/tuto…

​ One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you’re usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.

​ 匿名类的一个问题是,如果匿名类的实现非常简单,例如只包含一个方法的接口,那么匿名类的语法可能会显得笨拙和不清楚。在这些情况下,您通常会尝试将功能作为参数传递给另一个方法,例如当有人单击按钮时应该采取什么操作。 Lambda 表达式使您能够做到这一点,将功能视为方法参数,或将代码视为数据。

描述中包含了三层含义

  • lambda表达式是对匿名类的简化
  • lambda使用的前提
    • 一个接口
    • 接口中包含一个方法
  • lambda表达式的理解:将功能作为参数传递给另一个方法

示例代码

  • 创建并开启一个线程,使用匿名内部类的方式实现Runnable,重写run方法
1
2
3
4
5
6
7
8
java复制代码public static void main(String[] args) {
new Thread(new Runnable() { // 匿名内部类
@Override
public void run() {
System.out.println("我是线程开启执行的代码");
}
}).start();
}
  • Runnable接口中只有一个抽象方法run。用lambda表达式改写
1
2
3
4
5
6
7
java复制代码// @FunctionalInterface
// public interface Runnable {
// public abstract void run();
// }
public static void main(String[] args) {
new Thread(() -> System.out.println("我是线程开启执行的代码")).start();
}
  • 说明

image-20211122211356351

语法

基本语法

从上述案例中,使用lambda表达式是对Runnable接口中的run方法进行了重写

格式:(抽象方法的参数列表) -> {重写的代码}

示例代码

删除集合中大于3的元素

  • 匿名内部类
1
2
3
4
5
6
7
8
java复制代码List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list.removeIf(new Predicate<Integer>() {
@Override
public boolean test(Integer i) {
return i > 3;
}
});
System.out.println(list); // [1, 2, 3]
  • lambda表达式
1
2
3
java复制代码List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list.removeIf((Integer i) -> {return i > 3;});
System.out.println(list); // [1, 2, 3]
  • 说明

image-20211122215836842

简写语法

参数的简写

  • 抽象方法参数的个数
    • 空参:不省略。
    • 一个参数:省略小括号,省略参数类型。
      • 省略前:(Integer i) -> {}
      • 省略后:i -> {}
    • 多个参数:省略参数类型。
      • 省略前:(String a, Integer b) -> {}
      • 省略后: (a,b) -> {}

方法体的简写

  • 方法体中只有一行表达式:省略大括号、return、分号。
    • 省略前:(Integer i) -> {return i > 3;}
    • 省略后:i -> i > 3

示例代码

  • lambda表达式
1
2
3
java复制代码List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list.removeIf((Integer i) -> {return i > 3;});
System.out.println(list); // [1, 2, 3]
  • 简写
1
2
3
java复制代码List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list.removeIf(i -> i > 3);
System.out.println(list); // [1, 2, 3]

函数式接口

概述

函数式接口:有一个抽象方法的接口

jdk为函数式接口提供了注解:@FunctionalInterface。

注解作用在接口上,用于校验该接口是否为函数式接口

示例

  • Inter接口中包含两个抽象方法

image-20211122221857068

JDK 8 中新增的函数式接口

在java.util.function包中新增多个函数式接口

例如:Predicate、Supplier、Function、Consumer

原理

debug调试

  • Demo.java
1
2
3
4
5
6
7
java复制代码public class Demo {
public static void main(String[] args) {
new Thread(() -> {
System.out.println("我是线程启动后执行的代码");
}).start();
}
}
  • debug运行

image-20211123000547877

  • 说明
+ run:748,Thread(java.lang):调用Thread中的run方法
+ run:-1,1156060786(`org.example.Demo$$Lambda$1`):调用`Demo$$Lambda$1`中的run方法
+ `lambda$main$0:10`,Demo(org.example): 方法`lambda$main$0`中执行了 打印语句
  • 小结
+ `Demo$$Lambda$1`这个类中的run方法 调用 -----> `lambda$main$0`方法 -------> 执行 lambda表达式代码块的代码(打印语句)

保留lambda语句产生的字节码文件

  • java命令+参数。在硬盘中产生一个新的class文件(Demo$$Lambda$1.class)
1
shell复制代码java -Djdk.internal.lambda.dumpProxyClasses Demo.class

image-20211123001203190

  • 将该文件拖入的idea中
+ `Demo$$Lambda$1`是Runnable的实现类
+ run方法中调用`Demo.lambda$main$0()`方法![image-20211123001344875](https://gitee.com/songjianzaina/juejin_p6/raw/master/img/ff9a719fe2fd3db0c2131a34232b3bc2cc204513d24e047dc8d3bc66f4744023)

原理理解

image-20211123002803105

方法引用(Method references)

概述

官网对方法引用的描述

官网:docs.oracle.com/javase/tuto…

​ You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

​ 您可以使用 lambda 表达式来创建匿名方法。然而,有时 lambda 表达式除了调用现有方法之外什么都不做。在这些情况下,按名称引用现有方法通常会更清楚。方法引用使您能够做到这一点;它们是用于已具有名称的方法的紧凑、易于阅读的 lambda 表达式。

描述中包含两层含义

  • 方法引用,用于labmda表达式中
  • 前提:lambda 表达式除了调用现有方法之外什么都不做。(下一节语法中的案例进行说明)
    • lambda表达式中的参数调用方法
      • 示例:(String s) -> s.toLowerCase()
    • labmda表达式中的参数作为其他方法的参数
      • 示例:(Ineger i) -> String.valueOf(i)

语法

官网:docs.oracle.com/javase/tuto…

There are four kinds of method references:

Kind Syntax Examples
Reference to a static method ContainingClass::staticMethodName Person::compareByAge MethodReferencesExamples::appendStrings
Reference to an instance method of a particular object containingObject::instanceMethodName myComparisonProvider::compareByName myApp::appendStrings2
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName String::compareToIgnoreCase String::concat
Reference to a constructor ClassName::new HashSet::new

四种方法引用

种类 语法 示例
引用静态方法 类名::静态方法名 Person::compareByAge MethodReferencesExamples::appendStrings
对特定对象的实例方法的引用 对象名::方法名 myComparisonProvider::compareByName myApp::appendStrings2
对特定类型的任意对象的实例方法的引用 类名::方法名 String::compareToIgnoreCase String::concat
引用构造方法 类名::new HashSet::new

下面的案例中会用到Stream相关API,我们会在后续的文章中进行详细讨论。

  • 引用静态方法
1
2
3
4
5
6
7
8
java复制代码// 将集合中的Integer 转换为 String, 并收集到一个新的集合中
List<Integer> integerList = new ArrayList<>(Arrays.asList(1,2,3,4,5));
List<String> stringList = integerList.stream()
// 参数i 作为String静态方法valueOf的参数。并且lambda表达式中除了方法的调用以外其他什么都没做
// .map(i -> String.valueOf(i))
.map(String::valueOf) // 引用String类中的静态方法valueOf。类名::静态方法名
.collect(Collectors.toList());
System.out.println(stringList);
  • 对特定对象的实例方法的引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
java复制代码public class Demo {
public static void main(String[] args) {
Test test = new Test();
List<Integer> integerList = new ArrayList<>(Arrays.asList(1,2,3,4,5));
integerList.stream()
/*
1.与静态方法不同,要想使用Test类中的show方法 需要先有Test类的实例
2.参数i 作为test对象show方法的参数
3.并且lambda表达式中除了方法的调用以外其他什么都没做
*/
// .forEach(i -> test.show(i));
.forEach(test::show); // 引用test对象中的方法show。对象名::方法名
}
}

class Test{
public void show(Object o){
System.out.println(o);
}
}
  • 对特定类型的任意对象的实例方法的引用
1
2
3
4
5
6
7
8
9
10
11
java复制代码// 将集合中的元素转成大写,并收集到新的集合中
List<String> list = new ArrayList<>(Arrays.asList("a","b","c"));
List<String> list2 = list.stream()
/*
1.参数s 作为toUpperCase方法的调用者
2.并且lambda表达式中除了方法的调用以外其他什么都没做
3.引用的类型为参数s的数据类型String
*/
// .map(s -> s.toUpperCase())
.map(String::toUpperCase) // 引用String类中的方法toUpperCase。类名::方法名
.collect(Collectors.toList());
  • 引用构造方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
java复制代码// 将集合中的元素转成Person对象,并收集到新的集合中
public class Demo {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>(Arrays.asList("张三","李四","王五"));

List<Person> personList = stringList.stream()
/*
1.参数s 作为Person类构造方法的参数
2.并且lambda表达式中除了方法的调用以外其他什么都没做
*/
// .map(s -> new Person(s))
.map(Person::new) // 引用Person类中的构造方法。类名::new
.collect(Collectors.toList());
}
}

class Person{
private String name;

public Person(String name) {
this.name = name;
}
}

下期预告

Stream相关API和原理

欢迎关注公众号OpenCoder,来和我做朋友吧~❤😘😁🐱‍🐉👀

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%