日拱一卒:Lamdba 之 Optional 操作
2023-10-12 本文已影响0人
Tinyspot
1. Optional 类
public final class Optional<T> {
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
public T orElse(T other) {
return value != null ? value : other;
}
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
}
1.1 Optional to Stream
@Test
public void optionalToStream() {
List<OrderDTO> orders = Stream.of(new OrderDTO("A001", "1001", 0),
new OrderDTO("A002", "1002", 1),
new OrderDTO("A003", "1003", 1))
.collect(Collectors.toList());
String orderCode = Optional.ofNullable(orders)
.orElse(Collections.emptyList())
.stream()
.findFirst()
.map(OrderDTO::getOrderCode)
.orElse(null);
String orderCode2 = Optional.ofNullable(orders)
.orElseGet(Collections::emptyList)
.stream()
.findFirst()
.map(OrderDTO::getOrderCode)
.orElse(null);
// if (Optional.ofNullable(orders).isPresent()) {
if (orders != null) {
String orderCode3 = Optional.ofNullable(orders)
.get()
.stream()
.findFirst()
.map(OrderDTO::getOrderCode)
.orElse(null);
}
}
image.png
1.2 orElseGet(Supplier)
@Test
public void optionalElse() {
OrderDTO orderDTO = new OrderDTO("A001", "1001");
String orderCode = Optional.ofNullable(orderDTO)
.orElseGet(OrderDTO::new)
.getOrderCode();
}
2. map()
@Test
public void optionalMap() {
List<OrderDTO> orders = Stream.of(new OrderDTO("A001", "1001", 0),
new OrderDTO("A002", "1002", 1),
new OrderDTO("A003", "1003", 1))
.collect(Collectors.toList());
String orderCode = Optional.ofNullable(orders)
.map(list -> list.stream().findFirst().orElse(new OrderDTO()))
.map(OrderDTO::getOrderCode)
.orElse(null);
}
Optional.map() 源码
public final class Optional<T> {
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));
}
}
}