Eric
Eric

Reputation: 469

Doing OR with multiple conditions using Optional wrapper

I am trying to understand and use Java 8 - Optional feature. I would like to refactor this code block. Without Optional I have such a condition.

ClassA objA = findObject();
if(objA == null || objA.isDeleted()){
  throw Exception("Object is not found.");
}

I want to transform this block using Optional wrapper. I have read about filter, ifPresent functions but I could not find a way. Maybe it is simple but I am new to Java 8. I would appreciate if you could help.

Upvotes: 4

Views: 5121

Answers (3)

Ajay Kumar
Ajay Kumar

Reputation: 5243

      return list.stream()
        .filter(tmm -> tmpAddress.type() == 1)
        .findFirst()
        .orElseThrow(()->{
                logger.error("ERROR");//something like this
                exceptionHandler.handler("some exception
                return null;
        });

Upvotes: 0

Abdelghani Roussi
Abdelghani Roussi

Reputation: 2817

@Eric as you mentioned in your comment, if you don't want (can't) change the return type of findObject() for some constraints, you can do the following :

ClassA objA = findObject();
Optional<ClassA> myOpt = 
             Optional.ofNullable(objA)
                     .filter(e->!e.isDeleted())
                     .orElseThrow(()->new Exception("Object is not found.");

Upvotes: 3

Ousmane D.
Ousmane D.

Reputation: 56473

You shouldn't use Optional<T> to solely replace the if statement as it's no better and doesn't gain you any benefit. A much better solution would be to make the findObject() method return Optional<ClassA>.

This makes the caller of this method decide what to do in the "no value" case.

Assuming you've made this change, you can then leverage the Optional<T> type:

findObject().filter(a -> !a.isDeleted())  // if not deleted then do something 
            .map(...)  // do some mapping maybe?
            ...  // do some additional logic
            .orElseThrow(() -> new Exception("Object is not found."));//if object not found then throw exception

see the Optional<T> class to familiarise your self with the API and the methods that are available.

Upvotes: 8

Related Questions