How to perform null check in java 8

11.3k Views Asked by At

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);
}
2

There are 2 best solutions below

0
Andy Turner On BEST ANSWER

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.

5
Basil Bourque On

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 );