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);
}
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);
}
On
As the Answer by Andy Turner suggest, writing a plain null check is best here.
Objects.nonNullBut 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.requireNonNullElseGetAnother 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 );
You can do:
or
or
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.