How to perform null check in java 8

Srinivasa Moorthi V :

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);
}
Andy Turner :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=218378&siteId=1