0%

Lambda 表达式与函数式接口

视频教程笔记,视频地址见 深入理解 Java8+jdk8 源码级思想

Lambda 表达式

Lambda 表达式简介

介绍

Lambda 表达式可以认为是一种匿名函数(对 JAVA 而言,他是一个对象,此处暂且认为是一种匿名函数吧),简单地说,它是没有声明的方法,也即没有访问修饰符、返回值声明和名字。

作用

  1. 在 JAVA8 之前,无法将函数作为参数传递给一个方法,也无法声明返回一个函数的方法。Lambda 表达式为 JAVA 添加了缺失的函数式编程的特性,使我们能把函数作为一等公民看待
  2. 在将函数作为一等公民的语言中,Lambda 表达式的类型是函数。但是在 JAVA 中 Lambda 表达式是对象,他们必须依附于一类特别的对象类型——函数式接口。

Lambda 表达式的语法结构

  • 一个 Lambda 表达式可以有零个或多个参数
  • 参数的类型既可以明确声明,也可以根据上下文来推断。例如:(int a)(a)效果相同
  • 所有参数需包含在圆括号内,参数之间用逗号相隔。例如:(a, b)(int a, int b)(String a, int b, float c)
  • 空圆括号代表参数集为空。例如:() -> 42
  • 当只有一个参数,且其类型可推导时,圆括号 () 可省略。例如:a -> return a*a
  • Lambda 表达式的主体可包含零条或多条语句
  • 如果 Lambda 表达式的主体只有一条语句,花括号 {} 可省略。匿名函数的返回类型与该主体表达式一致
  • 如果 Lambda 表达式的主体包含一条以上语句,则表达式必须包含在花括号 `{} 中(形成代码块)。匿名函数的返回类型与代码块的返回类型一致,若没有返回则为空

函数式接口

函数式接口简介

定义

某个接口中有且只有一个抽象方法,此时该接口称为函数式接口。

如果接口中某个方法重写了 java.lang.Object 中的方法,则改方法不算接口的抽象方法。即下面代码声明的接口也是函数式接口

1
2
3
4
5
6
7
@FunctionalInterface
public interface MyInterface {
void test();

@Override
String toString();
}

几个知识点

  1. 如果在接口上添加了 FunctionalInterface 注解,则编译器会以函数式接口的定义来要求该接口
  2. 如果一个接口只有一个抽象方法,但是没有加上 FunctionalInterface注解,编译器也会认为该接口是函数式接口
  3. 函数式接口可以通过 lambda表达式、函数引用和构造函数引用的方式来创建

java8中常用的函数式接口

Function 接口详解

源码解析
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Represents a function that accepts one argument and produces a result.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object)}.
*
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
*
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R> {

/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);

/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function)
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}

/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}

/**
* Returns a function that always returns its input argument.
*
* @param <T> the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}

Function 函数接口一共有四个方法,其中有一个抽象方法,两个有 default 实现的方法,一个静态方法。

  1. R apply(T t) 接收一个 T 类型的参数,并有一个 R 类型的返回值
  2. <V> java.util.function.Function<V, R> compose(java.util.function.Function<? super V, ? extends T> before)<V> java.util.function.Function<T, V> andThen(java.util.function.Function<? super R, ? extends V> after) 提供了两种组合处理行为。前者是在调用自己的 apply 方法之前,先调用另外一个 Function 接口的 apply 方法;后者是先执行自己的 apply 方法,再执行另外一个 Function 接口的 apply 方法。值得注意的是,这两个函数返回的是一个实现了 apply 方法的新的 Function 对象,而不是直接返回计算后的结果,所以在调用了这两个方法后,还需要 .apply(T) 才能得到结果。
  3. <T> java.util.function.Function<T, T> identity() 用来直接返回输入的参数。
一个例子
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
package info.andrewei;

import java.util.function.Function;

/**
* @author Andrewei
*/
public class Main {
public static void main(String[] args) {
Main ma = new Main();
System.out.println(ma.compute1(2, value -> value * 3, value -> value * value));
System.out.println(ma.compute2(2, value -> value * 3, value -> value * value));
}

public int compute1(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(a);
}

public int compute2(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(a);
}
}

// 输出
// 3 * (2 * 2) = 12
// (2 * 3) ^ 2 = 36

BIFunction 接口详解

源码解析
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Represents a function that accepts two arguments and produces a result.
* This is the two-arity specialization of {@link Function}.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object, Object)}.
*
* @param <T> the type of the first argument to the function
* @param <U> the type of the second argument to the function
* @param <R> the type of the result of the function
*
* @see Function
* @since 1.8
*/
@FunctionalInterface
public interface BiFunction<T, U, R> {

/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);

/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}

可以类比 Function 来看。注意方法 <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) 的参数为 Function 类型。原因也比较容易理解,因为 andThen 方法会先执行自己的 apply 方法,再执行传入的 Function 接口的 apply 方法。执行自己的 apply 方法只会有一个 R 类型的返回值,所以后面的 apply 方法只能有一个入参。

一个例子
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
28
29
30
31
32
33
34
35
36
package info.andrewei;

import java.util.function.BiFunction;
import java.util.function.Function;

/**
* @author Andrewei
*/
public class Main {
public static void main(String[] args) {
Main ma = new Main();

System.out.println(ma.compute3(1, 2, (value1, value2) -> value1 + value2));
System.out.println(ma.compute3(1, 2, (value1, value2) -> value1 - value2));
System.out.println(ma.compute3(1, 2, (value1, value2) -> value1 * value2));
System.out.println(ma.compute3(1, 2, (value1, value2) -> value1 / value2));

System.out.println(ma.compute4(2, 3, (value1, value2) -> value1 + value2, value -> value * value));

}

public int compute3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
return biFunction.apply(a, b);
}

public int compute4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
return biFunction.andThen(function).apply(a, b);
}
}

// 输出
// 3
// -1
// 2
// 0
// 25

Predicate 接口详解

源码解析
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@FunctionalInterface
public interface Predicate<T> {

/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);

/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}

/**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
default Predicate<T> negate() {
return (t) -> !test(t);
}

/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}

/**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param <T> the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}

该接口主要用于做判断,即是否满足条件 这种场景,一共有5个方法

  1. boolean test(T t) 该方法接受一个 T 类型的入参,并返回 boolean
  2. Predicate<T> and(Predicate<? super T> other) 该方法允许传入另外一个 Predicate 接口,只有两个 Predicate 都判断为 true 时,才会返回 true,即 条件
  3. Predicate<T> or(Predicate<? super T> other) 对比上面的方法,上面的是 条件,这个函数是 条件
  4. Predicate<T> negate() 返回 !test(t)
  5. <T> Predicate<T> isEqual(Object targetRef) 判断两个 object 是否相等。一眼看上去会感觉比较奇怪,这个函数实际上是通过出入的参数 targetRef 生成一个 <T> Predicate<T> 对象,即固定了相比较的两个 object 中的一个 targetRef,后面再调用 .test(obj) 来判断是否相等。
一个例子
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package info.andrewei;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
* @author Andrewei
*/
public class Main {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

System.out.println(list.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(i -> i % 2 != 0).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(i -> i >= 5).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(i -> i < 3).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(i -> true).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(i -> false).collect(Collectors.toList()));
System.out.println("-----------------------");


Main ma = new Main();

System.out.println(list.stream().filter(item -> ma.and(item, i -> i> 5, i-> i % 2 == 0)).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(item -> ma.or(item, i -> i> 5, i-> i % 2 == 0)).collect(Collectors.toList()));
System.out.println("-----------------------");
System.out.println(list.stream().filter(item -> ma.negate(item, i -> i> 5, i-> i % 2 == 0)).collect(Collectors.toList()));
System.out.println("-----------------------");

Predicate<String> isStringEqual = Predicate.isEqual("string");
System.out.println(isStringEqual.test("string"));
System.out.println("-----------------------");
System.out.println(isStringEqual.test("string1"));
System.out.println("-----------------------");
}

public boolean and(int i, Predicate<Integer> p1, Predicate<Integer> p2) {
return p1.and(p2).test(i);
}

public boolean or(int i, Predicate<Integer> p1, Predicate<Integer> p2) {
return p1.or(p2).test(i);
}

public boolean negate(int i, Predicate<Integer> p1, Predicate<Integer> p2) {
return p1.and(p2).negate().test(i);
}
}

// 输出
//[0, 2, 4, 6, 8]
//-----------------------
//[1, 3, 5, 7, 9]
//-----------------------
//[5, 6, 7, 8, 9]
//-----------------------
//[0, 1, 2]
//-----------------------
//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//-----------------------
//[]
//-----------------------
//[6, 8]
//-----------------------
//[0, 2, 4, 6, 7, 8, 9]
//-----------------------
//[0, 1, 2, 3, 4, 5, 7, 9]
//-----------------------
//true
//-----------------------
//false
//-----------------------

Supplier 接口详解

源码解析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Represents a supplier of results.
*
* <p>There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #get()}.
*
* @param <T> the type of results supplied by this supplier
*
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {

/**
* Gets a result.
*
* @return a result
*/
T get();
}

这个接口很简单,只有一个抽象方法,T get() 获取一个对象,每次获取的对象可以是相同的,也可以是不同的。