Throw an exception if an Optional<> is present

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?


Solution 1:

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:

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:

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