How should we manage jdk8 stream for null values

前端 未结 5 1317
北海茫月
北海茫月 2020-12-04 10:53

Hello fellow Java developers,

I know the subject may be a bit in advance as the JDK8 is not yet released (and not for now anyway..) but I was reading som

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 11:29

    Although the answers are 100% correct, a small suggestion to improve null case handling of the list itself with Optional:

     List listOfStuffFiltered = Optional.ofNullable(listOfStuff)
                    .orElseGet(Collections::emptyList)
                    .stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
    

    The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList) will allow you to handle nicely the case when listOfStuff is null and return an emptyList instead of failing with NullPointerException.

提交回复
热议问题