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?
The orElseThrow() method of java. util. Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.
NoSuchElementException Exception Via orElseThrow() Since Java 10. Using the Optional. orElseThrow() method represents another elegant alternative to the isPresent()-get() pair. Sometimes, when an Optional value is not present, all you want to do is to throw a java.
The technique used in Optional for error handing is similar to the old one (in C or even go), returning error codes to handle exceptions. But instead of error code we return a generic type called Optional which indicates presence or absence of a value.
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"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With