简体   繁体   中英

Java Streams - check if list is null

I wonder what's teh best approach to check if list is null. In my Stream I call orElseThrow twice. It works but I don;t know if its correct? It looks a little bit ugly:

Optional.ofNullable(listCanBeNull)
                .orElseThrow(() -> new ResourceNotFoundException("the same error message"))
                .stream()
                .filter(configuration -> configuration.getId().equals(warehouseConfigurationId))
                .findAny()
                .orElseThrow(() -> new ResourceNotFoundException("the same error message"));

I have to throw error when list is null and when no item was found

Just check if the list is null directly. Streaming elements from a list only makes sense if the list exists in the first place.

if(null != listCanBeNull) {
    // stream things from here
}

An Optional.ofNullable can be turned into a (possibly empty) Stream, or you can immediately use Stream.ofNullable. And do a flatMap.

Stream.ofNullable(listCanBeNull)
        .stream()
        .flatMap()
        .filter(configuration -> couration.getId().equals(warehouseConfigurationId))
        .findAny()
        .orElseThrow(() -> new ResourceNotFoundException("the same error message"));

tl;dr

Objects.requireNonNull( list , "error message" ).stream() …  // Throws NullPointerException if null.

Details

If you choose to go with a simple null check before streaming, here is an alternative to the null check shown in correct Answer by Makoto .

Objects.nonNull

I find a call to Objects.nonNull to be more readable than null != list .

if ( Objects.nonNull( list ) ) { list.stream() … }

Objects.requireNonNull

Or automatically throw an exception if the object reference should never be null, with a call to Objects.requireNonNull .

 Objects.requireNonNull( list )  // Throws NullPointerException if null.

This method returns the object you pass (your list), providing for convenient method-chaining .

Objects.requireNonNull( list ).stream() … 

You can optionally pass a message to be used in the exception if thrown.

Objects.requireNonNull( list , "message goes here" ).stream() … 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM