2

I have created a method that checks if there is an element in the list with a specific id, and if it does not exist it throws an exception. I just do not know how to check if the match value is false, then throw an my exception AccessToMessageForbiddenException.

private void validMessage(Long messageId) { List<Message> messageList = messageService.findBySender(1L); messageList.addAll(messageService.findByRecipient(1L)); boolean match = messageList.stream().anyMatch(v -> messageId.equals(v.getId())); //How to throw an exception without an if construct } 
3
  • 11
    What's wrong with using an if statement? Commented Aug 2, 2017 at 13:19
  • Why can't you use an if statement ? Commented Aug 2, 2017 at 13:20
  • what about try catch? Commented Aug 2, 2017 at 13:21

2 Answers 2

7

You can use findAny() instead of anyMatch, and throw an exception if the resulting Optional is empty.

This doesn't require an if statement. Just use orElseThrow(), which throws an exception if the Optional is empty:

private void validMessage(Long messageId) { List<Message> messageList = messageService.findBySender(1L); messageList.addAll(messageService.findByRecipient(1L)); messageList.stream() .filter(v -> messageId.equals(v.getId())) .findAny() .orElseThrow(AccessToMessageForbiddenException::new); } 
Sign up to request clarification or add additional context in comments.

2 Comments

if the resulting Optional is empty. You said if! :-)
@Eran +1, but orElseThrow is still an if statement - internally. still this is much cleaner
0

You can get an optional of the Stream and use a consumer to throw an exception

Consumer<Message> d = t -> { throw new CustomException("Message: " + Message.toString()); }; messageList.stream().filter(yourFilterPredicate).findAny().ifPresent(d); 

Comments