jdk1.8_Optional

概述

主要用于解决空指针异常(NullPointerException)
类似包含有可选值的包装类,Optional 类既可以含有对象也可以为空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* A container object which may or may not contain a non-null value.
* If a value is present, {@code isPresent()} will return {@code true} and
* {@code get()} will return the value.
*
* <p>Additional methods that depend on the presence or absence of a contained
* value are provided, such as {@link #orElse(java.lang.Object) orElse()}
* (return a default value if value not present) and
* {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block
* of code if the value is present).
*
* <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Optional} may have unpredictable results and should be avoided.
*
* @since 1.8
*/
public final class Optional<T> {...}

of()&ofNullable()

构造带有值的Optional类
of()方法中的参数不允许为null,传入null会导致NullPointerException异常
若调用ofNullable()方法并传入空值则实际上相当于直接调用empty()方法实例化一个空的Optional

1
2
3
4
5
6
Optional<String> optional = Optional.of("value");
Optional<String> optionalNull = Optional.ofNullable(null);
Optional<String> emptyOpt = Optional.empty();
System.out.println(optional.get());//value
System.out.println(emptyOpt.get());//NoSuchElementException
System.out.println(optionalNull.get());//NoSuchElementException
1
2
3
4
5
6
7
8
9
10
11
12
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}

isPresent()&ifPresent()

isPresent() 判断是否为空
ifPresent() 判断是否为空,不为空则执行方法内的lambda表达式(实现消费型接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}

/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
1
2
3
4
Optional<String> optional = Optional.of("value");
Optional<String> optionalNull = Optional.ofNullable(null);
optional.ifPresent((s) -> System.out.println(s));//value
optionalNull.ifPresent(System.out::println);//不执行

orElse()&orElseGet()&orElseThrow()

orElse() 若Optional对象为空值则返回方法传入的值
orElseGet() 若Optional对象为空值则执行方法内的lambda表达式(供给型功能函数)
orElseThrow() 若Optional对象为空值则抛出指定的异常(供给型功能函数)

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
/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned if there is no value present, may
* be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}

/**
* Return the value if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no value
* is present
* @return the value if present otherwise the result of {@code other.get()}
* @throws NullPointerException if value is not present and {@code other} is
* null
*/
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}

/**
* Return the contained value, if present, otherwise throw an exception
* to be created by the provided supplier.
*
* @apiNote A method reference to the exception constructor with an empty
* argument list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier The supplier which will return the exception to
* be thrown
* @return the present value
* @throws X if there is no value present
* @throws NullPointerException if no value is present and
* {@code exceptionSupplier} is null
*/
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
1
2
3
4
5
6
7
8
Optional<String> optionalNull = Optional.ofNullable(null);
System.out.println(optionalNull.orElse("值为null"));//值为null
System.out.println(optionalNull.orElseGet(()->"值为null"));
try {
optionalNull.orElseThrow(Exception::new);
} catch (Exception e) {
e.printStackTrace();
}

map()&flatMap()

map()方法,若传入的方法存在值,则返回方法对应类型的Optional对象,否则返回一个空的Optional
同样,但入参需要是Optional对象

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
/**
* If a value is present, apply the provided mapping function to it,
* and if the result is non-null, return an {@code Optional} describing the
* result. Otherwise return an empty {@code Optional}.
*
* @apiNote This method supports post-processing on optional values, without
* the need to explicitly check for a return status. For example, the
* following code traverses a stream of file names, selects one that has
* not yet been processed, and then opens that file, returning an
* {@code Optional<FileInputStream>}:
*
* <pre>{@code
* Optional<FileInputStream> fis =
* names.stream().filter(name -> !isProcessedYet(name))
* .findFirst()
* .map(name -> new FileInputStream(name));
* }</pre>
*
* Here, {@code findFirst} returns an {@code Optional<String>}, and then
* {@code map} returns an {@code Optional<FileInputStream>} for the desired
* file if one exists.
*
* @param <U> The type of the result of the mapping function
* @param mapper a mapping function to apply to the value, if present
* @return an {@code Optional} describing the result of applying a mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null
*/
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}

/**
* If a value is present, apply the provided {@code Optional}-bearing
* mapping function to it, return that result, otherwise return an empty
* {@code Optional}. This method is similar to {@link #map(Function)},
* but the provided mapper is one whose result is already an {@code Optional},
* and if invoked, {@code flatMap} does not wrap it with an additional
* {@code Optional}.
*
* @param <U> The type parameter to the {@code Optional} returned by
* @param mapper a mapping function to apply to the value, if present
* the mapping function
* @return the result of applying an {@code Optional}-bearing mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null or returns
* a null result
*/
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
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
class FlightTicketInfo {

private String orderNumber;

public String getOrderNumber() {
return orderNumber;
}

}

public class OptionalTest {

@Test
public void testMap() {
FlightTicketInfo flightTicketInfo = null;

Optional<Optional<String>> s1 = Optional.ofNullable(flightTicketInfo).
map(OptionalTest::getOrderNumber);

Optional<String> s2 = Optional.ofNullable(flightTicketInfo).
map(FlightTicketInfo::getOrderNumber);

Optional<String> s3 = Optional.ofNullable(flightTicketInfo).
flatMap(OptionalTest::getOrderNumber);
}

private static Optional<String> getOrderNumber(FlightTicketInfo flightTicketInfo) {
return Optional.ofNullable(flightTicketInfo).map(f -> f.getOrderNumber());
}

}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020 李明华
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信