Search code examples
javaoption-type

How to check if an optional value is present and equal to another value


Is there a way to express the below conditional in a more concise fashion?

    Optional<Order> order = getOrder(); // API Call
    if (
      order.getCustomer().isPresent() &&
      order.getCustomer().get().equals(INTERNAL_CUSTOMER)
    ) {
      return;
    }

Solution

  • You can use the lambda expression using map and filter. map is used to pull/manipulae actual data coming from stream and filter will be used for predicating the value if it's true or false, isPresent will return true if stream returned any result after filter

    if (order.map(Order::getCustomer).filter(INTERNAL_CUSTOMER::equals).isPresent()) { ... }