Search code examples
javaoption-type

how to compare Optional<Long> with Long


I need to compare two cities ids. The first one is Optional < Long>, the second one is Long.

  public boolean isEqual(Comment comment) {
    return userService.findById(comment.getUser().getId())
        .map(user -> user.getCity().getId()) // Optional <Long>
        .filter(user -> user
            .equals(postService.findById(comment.getPost().getId())
                .map(p -> p.getUser().getCity().getId())))  // Long
        .isPresent();
  }

How can I do this?


Solution

  • You could compare optionals directly:

    public boolean isEqual(Comment comment) {
      Optional<Long> userCityFromComment = userService
        .findById(comment.getUser().getId())
        .map(user -> user.getCity().getId());
      Optional<Long> userCityFromPost = postService
        .findById(comment.getPost().getId())
        .map(p -> p.getUser().getCity().getId());
      return userCityFromComment.equals(userCityFromPost);
    }
    

    Note that Optional.empty().equals(Optional.empty()) is true.