I have a nullable object and I'm trying to throw an exception if the object is not null
and does not meet a condition.
I try this way with Optional
:
Optional.ofNullable(nullableObject)
.filter(object -> "A".equals(object.getStatus()))
.orElseThrow(() -> new BusinessUncheckedException("exception message"));
When the object is not null
, it works as I want, but otherwise, it throws the exception too (and I don't want that).
There is a way to do that with Optional
or other ways not using if object != null
?
The filter() method of java. util. Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance.
In Java, the Optional object is a container object which may or may not contain a value. The Optional class is present in the java.
isPresent() returns true if the given Optional object is non-empty. Otherwise it returns false. Optional. ifPresent() performs given action if the given Optional object is non-empty.
If you just want an Optional returning false for isPresent() , you don't need to mock the Optional at all but just create an empty one. Of course this test only tests that the mock object actually returns the stubbed return value, but you get the idea.
Filtering a Stream of Optionals in Java 1 Introduction. In this article, we're going to talk about how to filter out non-empty values from a Stream of Optionals. 2 Using filter () 3 Using flatMap () List<String> filteredList = listOfOptionals.stream () .flatMap (o -> o.isPresent () ? 4 Java 9's Optional::stream. ... 5 Conclusion. ...
The Java 8 Optional class has a method filter () which takes Predicate as an argument. Optional is a class and it is in java.util package. Optional is declared as final in its source code. Because no other classes can be inherited and to stop overriding the behavior.
Using filter () One of the options in Java 8 is to filter out the values with Optional::isPresent and then perform mapping with the Optional::get function to extract values: List<String> filteredList = listOfOptionals.stream () .filter (Optional::isPresent) .map (Optional::get) .collect (Collectors.toList ());
Optional ifPresentOrElse () method in Java with examples. The ifPresentOrElse (Consumer, Runnable) method of java.util. Optional class helps us to perform the specified Consumer action the value of this Optional object. If a value is not present in this Optional, then this method performs the given empty-based Runnable emptyAction, ...
Assuming you aren't doing anything with the returned object, you could use ifPresent
and pass a Consumer
nullableObject.ifPresent(obj -> {
if (!"A".equals(obj.getStatus())) {
throw new BusinessUncheckedException("exception message");
}
});
Note: As @Pshemo mentioned in the comments, the contract of the Consumer
functional interface allows throwing only RuntimeExceptions.
Otherwise, you are better off with a if check as you've mentioned.
IMO, using a filter
on Optional for checks like these is not that readable/intuitive. I would prefer,
if (obj != null && !"A".equals(obj.getStatus())) {
throw new BusinessUncheckedException("exception message");
}
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