How to pick the value from ifPresent of Optional

How do I pick the value from the method ifPresent, as this method returns void?

The logic that I want to apply is: If the object deliveryInfo is not null, take the delivery quantity and set it into the object dto, but using Optional, without any null check.

Optional<TT021DeliveryCodingContainerDto> deliveryInfo =
    tt021OrderingBusinessHandler
        .getDeliveryCodingContainersByDeliveryAndOrderDetail(
            delivery.getId(), position.getOrderDetails().getId());
deliveryInfo.ifPresent(TT021DeliveryCodingContainerDto::getDeliveredQuantity);
dto.setQuantityDelivered(deliveredQuantity);

Answer

Something like deliveryInfo.ifPresent(i -> dto.setQuantityDelivered(i.getDeliveredQuantity());?

If you want to return something from the method, use map instead of ifPresent; this will return another Optional wrapping the result (if any).

Leave a Reply

Your email address will not be published. Required fields are marked *