Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional filter only if present

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?

like image 614
Victor Soares Avatar asked Nov 06 '21 14:11

Victor Soares


People also ask

Is filter method present in optional class?

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.

Is present Java optional?

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.

What is difference between isPresent and ifPresent?

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.

How do I make optional isPresent false?

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.

How to filter a stream of optionals in Java?

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. ...

What is an optional method in Java 8?

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.

How do I filter a list of options in Java 8?

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 ());

What is optional ifpresentorelse method in Java with examples?

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, ...


Video Answer


1 Answers

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");
}
like image 170
user7 Avatar answered Oct 06 '22 01:10

user7