今週、私は Optional の興味深い「新しい」機能について学びました。この機能についてこの投稿でお話したいと思います。Java 9 から使用可能になっているため、新しさは相対的です。
合計注文価格を計算するための次のシーケンスから始めましょう。
public BigDecimal getOrderPrice(Long orderId) {
List<OrderLine> lines = orderRepository.findByOrderId(orderId);
BigDecimal price = BigDecimal.ZERO;
for (OrderLine line : lines) {
price = price.add(line.getPrice());
}
return price;
}
価格に可変アキュムレータを提供
各行の価格を合計価格に追加します
, , . :
public BigDecimal getOrderPrice(Long orderId) {
List<OrderLine> lines = orderRepository.findByOrderId(orderId);
return lines.stream()
.map(OrderLine::getPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
orderId
: null
.
null
, - :
public BigDecimal getOrderPrice(Long orderId) {
if (orderId == null) {
throw new IllegalArgumentException("Order ID cannot be null");
}
List<OrderLine> lines = orderRepository.findByOrderId(orderId);
return lines.stream()
.map(OrderLine::getPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
, orderId
Optional. Optional:
public BigDecimal getOrderPrice(Long orderId) {
return Optional.ofNullable(orderId)
.map(orderRepository::findByOrderId)
.flatMap(lines -> {
BigDecimal sum = lines.stream()
.map(OrderLine::getPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return Optional.of(sum);
}).orElse(BigDecimal.ZERO);
}
orderId
Optional
flatMap()
,Optional<BigDecimal>
;map()
Optional<Optional<BigDecimal>>
Optional
, .
Optional
,0
Optional
! , .
, Optional
stream()
( Java 9). :
public BigDecimal getOrderPrice(Long orderId) {
return Optional.ofNullable(orderId)
.stream()
.map(orderRepository::findByOrderId)
.flatMap(Collection::stream)
.map(OrderLine::getPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
:
, . , , , .
"Java Developer. Basic". , , .