考虑有null值,但是要转换字段类型取值,都可以用这种方法: loyTxnStg.setOrigPoints(Optional.ofNullable(source.getOrigPoints()).map(BigDecimal::valueOf).orElse(null)); 或者: memTier.setSeqNum(Objects.requireNonNullElse(tier, Tier::new).getSeqNum()); 或者: String birthDay = StringUtils.defaultIfEmpty(contact.getCustomBirthdayDay(), "1"); 或者: String pointValue = posReqVO.getAccount1000Value() == null? "0":posReqVO.getAccount1000Value(); String pointValue = Optional.ofNullable(posReqVO.getAccount1000Value()).orElse("0"); 优化 if else,不想用if else,也可以考虑用函数式断言Predicate或BiPredicate 校验。 1:用三元运算和 Consumer 改造: Consumer<List<CustomerLoyOrderTxnPO>> insertOperation = posConfirmPointVO.getIsRepeatedOrderFlag() ? orderTxnRepository::signleInsertLoyCustomerTxnOrder : orderTxnRepository::batchInsertLoyCustomerTxnOrder; insertOperation.accept(orderTxnsList); 2:使用三元运算符,最简单实现。 3:用Predicate检验改造: // 判断是否重复订单的条件 Predicate<PosConfirmPointVO> isRepeatedOrder = PosConfirmPointVO::getIsRepeatedOrderFlag; // 定义处理重复订单的逻辑 Runnable handleRepeatedOrder = () -> checkInsertCustomerBueventTxn(bueventTxnPO, account, buEventAccountDefnXmPOS); // 定义处理非重复订单的逻辑 Runnable handleNonRepeatedOrder = () -> { customerBueventTxnRepository.insertCustomerBueventTxn(bueventTxnPO); upsertBueventAccountByType(memberId, eventId, account, buEventAccountDefnXmPOS); }; // 根据订单是否重复执行不同的逻辑,不想用if(isRepeatedOrder.test(posConfirmPointVO)){} Optional.of(posConfirmPointVO) .filter(isRepeatedOrder) .ifPresentOrElse( result -> handleRepeatedOrder.run(), () -> handleNonRepeatedOrder.run() );
1. 旧代码:
String authToken = getAuthToken();
updateApolloConfig(count, authToken, apolloServiceConfig.parseItemUrl());
if (isUpdateBlue) {
updateApolloConfig(count, authToken, apolloServiceConfig.parseBlueItemUrl());
}
这样不更好:
Stream.of(apolloServiceConfig.parseItemUrl(),
isUpdateBlue ? apolloServiceConfig.parseBlueItemUrl() : Stream.empty())
.forEach(url -> updateApolloConfig(count, getAuthToken(), url));
2. 旧代码:
List<Account> accounts = posConfirmReqVO.getAccounts();
if (accounts.isEmpty()) {
return;
}
accounts.stream()
.filter(acc -> "1000".equals(acc.getId()))
.findFirst()
.ifPresent(x -> posConfirmReqVO.setAccount1000Value(x.getEarnValue()));
这样更好:
Optional.ofNullable(posConfirmReqVO.getAccounts())
.filter(accounts -> !accounts.isEmpty())
.flatMap(accounts -> accounts.stream()
.filter(acc -> "1000".equals(acc.getId()))
.findFirst())
.ifPresent(x -> posConfirmReqVO.setAccount1000Value(x.getEarnValue()));