Throw an exception if an Optional<> is present

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");
            });

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


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");
}

Tags:

Java

Java 8