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?