简体   繁体   中英

How to perform null check in java 8

How to write below code in java 8

List<String> names = service.serviceCall();

if(names != null) { // **how to do this null check with java 8**
    names.forEach(System.out::println);
}

You can do:

Optional.ofNullable(names).orElse(Collections.emptyList()).forEach(System.out::println);

or

Optional.ofNullable(names).ifPresent(n -> n.forEach(System.out::println));

or

Stream.of(names)
    .filter(Objects::nonNull)
    .flatMap(Collection::stream)
    .forEach(System.out::println);

but don't. Look at all all that extra stuff you'd have to write.

Just use a plain old null check, like you have in your code already.

As the Answer by Andy Turner suggest, writing a plain null check is best here.

Objects.nonNull

But Java 8 does offer one minor improvement: methods on the Objects utility class for the null check.

So your code would like this.

List<String> names = service.serviceCall();

if( Objects.nonNull( names ) ) 
{   
    names.forEach( System.out::println );
}

Objects.requireNonNullElseGet

Another method on Objects can return an alternate object if that suits your situation. For example, if your service call returns null list, perhaps you should substitute an empty list. Call Objects.requireNonNullElseGet .

The lambda passed is handled in a lazy manner, not executed unless needed.

List<String> names = 
        Objects.requireNonNullElseGet
        ( 
            service.serviceCall() , 
            () -> new ArrayList<>( 0 )  // In Java 9 and later, use `List.of()`.
        )
;
names.forEach( System.out::println );

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