-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalMethods.java
More file actions
64 lines (53 loc) · 2.02 KB
/
OptionalMethods.java
File metadata and controls
64 lines (53 loc) · 2.02 KB
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
package chapter8.optionals;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Optional 方法 <br>
* 有几个 Optional 的方法来处理更特殊的用例:filter、map、flatMap 和 ifPresent isPresent()。在 Java 9 中,又添加了两个这样的方法:or 和 ifPresentOrElse
*/
public class OptionalMethods {
public static void main(String[] args) {
// filterM();
mapM();
flatMapM();
ifPresentM();
isPresentM();
}
static void filterM() {
opStrBlank().filter(String::isBlank).orElseThrow(() -> new RuntimeException("字符串为空"));
opEmpty().filter(String::isBlank).orElseThrow(() -> new RuntimeException("字符串为空"));
}
static void mapM() {
Stream<String> stringStream = opStr().map(String::lines).orElse(Stream.empty()); // 此处ide会提示使用flatMap函数替代,因为入参和出参类型发生了变化
stringStream.map(it -> it + "\t" + it.length()).forEach(System.out::println);
}
/**
* flatMap 接受一个 入参为原类型T,出参为另一个类型的 Optional<U>
*/
static void flatMapM() {
Integer i = opStr().flatMap(str -> str.lines().map(String::length).max(Integer::compareTo)).orElse(-1);
System.out.println(i);
}
/**
* ifPresent 参数为一个 consumer 消费者 <br>
* 如果存在则进行消费,不存在则不消费
*/
static void ifPresentM() {
opEmpty().ifPresent(System.out::println);
opStrBlank().ifPresent(System.out::println);
opStr().ifPresent(System.out::println);
}
static void isPresentM() {
System.out.println(opEmpty().isPresent());
System.out.println(opStrBlank().isPresent());
}
private static Optional<String> opStr() {
return Optional.of("abcd\n124");
};
private static Optional<String> opStrBlank() {
return Optional.of("");
}
private static Optional<String> opEmpty() {
return Optional.empty();
}
}