Throw an exception if an Optional<> is present

JavaJava 8

Java Problem Overview


Let's say I want to see if an object exists in a stream and if it is not present, throw an Exception. One way I could do that would be using the orElseThrow method:

List<String> values = new ArrayList<>();
values.add("one");
//values.add("two");  // exception thrown
values.add("three");
String two = values.stream()
        .filter(s -> s.equals("two"))
        .findAny()
        .orElseThrow(() -> new RuntimeException("not found"));

What about in the reverse? If I want to throw an exception if any match is found:

String two = values.stream()
        .filter(s -> s.equals("two"))
        .findAny()
        .ifPresentThrow(() -> new RuntimeException("not found"));

I could just store the Optional, and do the isPresent check after:

Optional<String> two = values.stream()
        .filter(s -> s.equals("two"))
        .findAny();
if (two.isPresent()) {
    throw new RuntimeException("not found");
}

Is there any way to achieve this ifPresentThrow sort of behavior? Is trying to do throw in this way a bad practice?

Java Solutions


Solution 1 - Java

You could use the ifPresent() call to throw an exception if your filter finds anything:

    values.stream()
            .filter("two"::equals)
            .findAny()
            .ifPresent(s -> {
                throw new RuntimeException("found");
            });

Solution 2 - Java

Since you only care if a match was found, not what was actually found, you can use anyMatch for this, and you don't need to use Optional at all:

if (values.stream().anyMatch(s -> s.equals("two"))) {
    throw new RuntimeException("two was found");
}

Solution 3 - Java

userOptional.ifPresent(user1 -> {throw new AlreadyExistsException("Email already exist");});

Here middle bracket is compulsory, else it is showing compile time exception

{throw new AlreadyExistsException("Email already exist");}

public class AlreadyExistsException extends RuntimeException

and exception class must extends runtime exception

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmkobitView Question on Stackoverflow
Solution 1 - JavaberesfordtView Answer on Stackoverflow
Solution 2 - JavaStuart MarksView Answer on Stackoverflow
Solution 3 - Javaasifaftab87View Answer on Stackoverflow