I have a method that takes an object having an ArrayList inside:
private List<String> getWatchlistDetail(MatchData k) {
if(k == null)
return new ArrayList<>();
return
k.getWatchListDetail()
.stream()
.collect(Collectors.toList());
}
MatchData k can be null, and sometimes k.getWatchListDetail() also could be null.
I need to check both condition. First, if it can throw NPE.
Above implementation does it, but I am trying to use perhaps Optional.ofNullable() or streams with chaining, so I can do it in one line of chaining.
Sure, you can check both in a single stream statement.
But, keep in mind:
Now compare it with the method below, which neither hides null-checks, no abuses streams and optional:
Functional programming was introduced in Java to reduce complexity of code, not the opposite, using it only for the purpose of hiding null-checks would not bay you anything.
By itself, null-check are not a problem, but only an indicator of a problem. And to address it, need to refine the design of your application.
In regard to the question whether it's possible to utilize optional in order to avoid conditional logic, take a look at this answer by @StuartMarks (JDK developer):