Reputation: 469
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
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
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
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