Reputation: 731
Little new to Java 8 style;
How effectively, we can code for the below statement by including all the null checks usin Java 8 API
search.getResource()
.getResults().get(0).getCustomer().getPhoneNumber()
I tried like following: (Looks little weird to me with Optional everywhere)
List<Result> results = search.getResource().getResults();
Optional<Result> optionalResult = Optional.of(results).orElse(new ArrayList<>()).stream().findFirst();
if(optionalResult.isPresent() && Optional.of(optionalResult.get().getCustomer()).isPresent()) {
Source source = Optional.of(optionalResult.get().getCustomer()).get();
Optional<List<Customer>> customers = Optional.of(source.getCustomers());
if(customers.isPresent() && customers.get().stream().findFirst().isPresent() &&
Optional.of(customers.get().stream().findFirst().get().getPhoneNumber()).isPresent())
dest.setNumber(Integer.parseInt(customers.get().stream().findFirst().get().getPhoneNumber())));
}
Could you please suggest me a better way of doing. Thanks!
Upvotes: 0
Views: 89
Reputation: 15622
OT: Why don't you simply code null safe?
Coding null safe means that you never explicitly retun a (literal) null
from a method or pass one in as a parameter. Furthermore you always do you null
checks on local variables before you pass them around or return them.
On Map
collections you use getOrDefault
or computeIfAbsent
to replace the null
returned for missing keys with a Null Equivalent Constant of the expected type.
Usually passing null
back and forth is a in band signal for an error condition which Java has exceptions for.
And no: passing around Optional
is not a solution, but another incarnation of the problem. Optional
is an elegant way to deal with variables than may contain null
within a method.
Don't let it escape...
Upvotes: 2
Reputation: 11496
You can use the map
method of Optional
class:
final Optional<String> optional = Optional.ofNullable(search.getResource())
.map(resource -> resource.getResults())
.map(results -> results.size() > 0 ? results.get(0) : null)
.map(result -> result.getCustomer())
.map(customer -> customer.getPhoneNumber());
optional.ifPresent(phoneNumber -> {
System.out.println(phoneNumber);
});
Upvotes: 7