本质: 内部包装了一个引用型对象, 封装了很多对null判断及转化的API
1. 构建
Optional of(T value) #value必须非null
Optional ofNullable(T value) #value可以为null
2. 空处理
boolean isPresent() #判断是否为null
void ifPresent(Consumer<? super T> consumer) #如果不为null再做处理
3. 转换
Optional filter(Predicate<? super T> predicate)
#如果value不为null且满足入参的predicate则返回当前Optional, 返回返回空的Optional
Optional map(Function<? super T, ? extends U> mapper)#如果value为null返回空的Optional, 如果不为null返回入参function的返回值再包装成Optional
Optional flatMap(Function<? super T, Optional> mapper)#如果value为null返回空的Optional, 如果不为null返回入参function的返回值(已经是Optional)
4. 获取
T get() #value必须非null, 如果为null直接异常
T orElse(T other) #如果value不为null直接返回,为null返回入参
T orElseGet(Supplier<? extends T> other) #如果value不为null直接返回,为null返回入参包装的值
T orElseThrow(Supplier<? extends X> exceptionSupplier) #如果value不为null直接返回,为null返回入参包装的异常
5. 场景
- 规避简单的if
List<ThriftChannelProductItemViewDto> channelProductItemViewDtos = channelProductItemQueryService.findByProductItemIds(itemIds, ChannelType.BTB.getId());
Map<Long, ThriftChannelProductItemViewDto> channelProductItemViewDtoMap = channelProductItemViewDtos.stream().collect(Collectors.toMap(ThriftChannelProductItemViewDto::getItemId, s -> s));
for (ThriftPricedOrderLineDto priceOrderLine : priceOrderLines) {
B2bOrderLineDto b2bOrderLineDto = new B2bOrderLineDto();
ThriftChannelProductItemViewDto productItemViewDto = channelProductItemViewDtoMap.get(priceOrderLine.getItemId());
//1.用if
if(productItemViewDto !=null){
b2bOrderLineDto.setItemName(productItemViewDto.getSkuName());
b2bOrderLineDto.setReturnWareHouseCode(productItemViewDto.getReturnWarehouseCode());
}
//2.用Optional
b2bOrderLineDto.setItemName(Optional.ofNullable(productItemViewDto).map(ThriftChannelProductItemViewDto::getSkuName).orElse(null));
b2bOrderLineDto.setReturnWareHouseCode(Optional.ofNullable(productItemViewDto).map(ThriftChannelProductItemViewDto::getReturnWarehouseCode).orElse(null));
}