Optional方法详解

本质: 内部包装了一个引用型对象, 封装了很多对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));	
            
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值