Java8新特性——lambda范围和内置功能接口

lambda scopes

在lambda表达式中我们可以访问外部变量,这个功能和匿名内部类一样,但是对于匿名内部类,我们只能访问final变量,lambda表达式中都可以访问,但是它只是隐式地将变量变成了final

首先我们能通过lambda表达式来访问外部变量。

1
2
3
4
5
6
7
8
9
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
public static void main(String[] args) {
int num = 1;
Converter<Integer, String> converter = (from -> String.valueOf(from + num));
System.out.println(converter.convert(2)); // 输出3
}
}

但是我们不能再改变lambda表达式中调用的外部变量了,因为一旦被lambda表达式调用,这个变量就被隐式地声明成了final变量。

1
2
3
4
5
6
7
8
9
10
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
public static void main(String[] args) {
int num = 1;
Converter<Integer, String> converter = (from -> String.valueOf(from + num));
System.out.println(converter.convert(2));
num = 3;
}
}

这个时候就会报错 从lambda 表达式引用的本地变量必须是最终变量或实际上的最终变量。

还有一个容易混淆的点就是这样的写法

1
2
3
4
5
6
7
public static void main(String[] args) {
int num = 1;
Converter<Integer, String> converter = String::valueOf;
System.out.println(converter.convert(2 + num));
num = 2;
System.out.println(num);
}

即使是对象也是一样

1
2
3
4
5
6
7
8
9
10
11
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder("123");
Converter<StringBuilder, String> converter = (stringBuilder1) -> stringBuilder1.toString();
System.out.println(converter.convert(stringBuilder));
stringBuilder.append("234");
System.out.println(stringBuilder);
}
}

这个时候其实我们只是将num作为函数参数传进去了,在lambda表达式中并没有显示声明调用这个变量。

在lambda表达式中我们还可以访问静态和类中的字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Lambda4 {
static int outerStaticNum;
int outerNum;

void testScopes() {
Converter<Integer, String> stringConverter1 = (from) -> {
outerNum = 23;
return String.valueOf(from);
};

Converter<Integer, String> stringConverter2 = (from) -> {
outerStaticNum = 72;
return String.valueOf(from);
};
}
}

还记得上次声明的Formula接口么,其中定义了一个sqrt的默认方法,在lambda中我们是不能调用默认方法的。

1
Formula formula = (a) -> sqrt(a * 100); //这样编译不通过

Built-in Functional Interfaces

Predicate

这是断言,判断的意思。先上代码

1
2
3
4
5
6
7
8
9
10
Predicate<String> predicate = (s) -> s.length() > 0;

predicate.test("foo"); // true
predicate.negate().test("foo"); // false

Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;

Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();

其中test方法就是Predicate接口中的唯一抽象方法,我们lambda表达式中就是实现了它。

negate方法是取反的意思,其中还有and(), or()这两个默认方法对应语,或。

可以直接看源代码

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);
}
}

Function

Function从字面理解就是函数的意思,这也是Java支持函数式编程的一个很重要的函数式接口。我们先看源码。

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
@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;
}
}

其中apply()是我们需要实现的一个函数,为什么这里说是函数不是方法呢?我们现在用函数式的思想去思考这个问题,其实这个方法就是我们给定一个参数然后我们返回一个结果,具体这个函数是怎么实现我们先不管。这就是函数式思想(先考虑参数和结果,然后再去考虑实现行为)。

这是作者给的实例代码

1
2
3
4
5
// 这里是实现apply方法
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);

backToString.apply("123"); // "123"

这里多出来了个andThen方法,我们来具体看一看

1
2
3
4
5
6
7
8
9
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
//判空
Objects.requireNonNull(after);
// 我们传入的是一个Function
// 该语句是先调用当前Function的apply方法
// 然后将该方法的返回值作为after(传入的Function)的apply方法中的参数
// 最终返回的是after的apply方法的返回值
return (T t) -> after.apply(apply(t));
}

里面还有一个compose方法,其实和andThen方法正好相反

1
2
3
4
5
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
// 先调用传入的befor的apply方法,然后将返回值作为当前Function的apply的参数
return (V v) -> apply(before.apply(v));
}

Supplier

这个函数很简单,就相当于无参函数,我们不需要设置给定参数,只关注结果

具体源码也很简单

1
2
3
4
5
6
7
8
9
10
@FunctionalInterface
public interface Supplier<T> {

/**
* Gets a result.
*
* @return a result
*/
T get();
}
1
2
Supplier<Person> personSupplier = Person::new;
personSupplier.get(); // new Person

Comsumer

我们先来看一下源码

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
@FunctionalInterface
public interface Consumer<T> {

/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);

/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}

上面有一个accept()是我们需要实现的抽象方法,其实就是我们给定一个参数但是我们没有返回值,然后这个andThen()就是传入一个Consumer先调用原来的Consumer的accept方法然后再调用传入的accept()

Comparators

1
2
3
4
5
6
7
8
9
// 这里是实现了compare方法
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);

Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");

comparator.compare(p1, p2); // > 0
// reversed方法是默认方法
comparator.reversed().compare(p1, p2); // < 0
-------------本文结束感谢阅读-------------