How to handle nullable lists using java 8?

Kyle Bak :

I'm making a service call and trying to handle response. Response might have a list of something. That list might be null.

Moreover, if list not null or not empty, then it needs to be filtered. In the code "entry" reference might be null if filtering gives nothing or response list is empty or null.

Currently i'm getting NPE when i try to use stream() on a null response list. How can i handle this situation?

@Getter
public class ServiceResponse {  
    List<ResponseEntry> entryList;
}

@Getter
public class ResponseEntry {
    String value;
}


ServiceResponse serviceResponse = service.getServiceResponse();
ResponseEntry entry = serviceResponse.getEntryList()
    .stream()
    .filter(e -> "expectedValue".equals(e.getValue()))
    .findFirst()
    .orElse(null);

if (entry == null) { ... }

Ousmane D. :

if list not null or not empty, then it needs to be filtered.

No need for Optional here, as it's not intended to replace simple if checks.

ResponseEntry entry = null;
List<ResponseEntry> responseEntries = serviceResponse.getEntryList();
if(responseEntries != null && !responseEntries.isEmpty()){
    entry = responseEntries.stream()
                .filter(e -> "expectedValue".equals(e.getValue()))
                .findFirst()
                .orElse(null);
}
  • reads "if responseEntries is not null and responseEntries is not empty then apply the filter operation and find the first item or else null". Very readable.

On the other hand, the optional approach:

ResponseEntry entry = Optional.ofNullable(serviceResponse.getEntryList())
                              .orElseGet(() -> Collections.emptyList())
                              .stream()
                              .filter(e -> "expectedValue".equals(e.getValue()))
                              .findFirst();

if(!entry.isPresent()){ ... } // or entry.ifPresent(e -> ...) depending on the logic you're performing inside the block
  • unnecessarily creates objects that could be avoided and not really the intention of optional to be used as a substitute for simple "if" checks.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36303&siteId=1