javaspringlistjava-stream

How to check if a property of a list is null using a proper approach?


I have the following method in my Java app:

private void save(final CopyRequest request) {

    if (request.getName() != null) {
        // stuff
    }
}

I update this method by converting the method parameters to List<CopyRequest> as shown below:

private void save(final List<CopyRequest> requestList) {

    if (requestList.getName() != null) {
        // stuff
    }
}

So, should I check if the name property is null via requestList.stream().forEach(request -> request.getName == null) or something like that?


Solution

  • You can use Stream#allMatch.

    if(requestList != null 
        && requestList.stream().allMatch(request -> request != null 
                && request.getName() != null)){
    
    }