One more way to write this with optional, in addition to correct @Murenik's answer. No need to create empty list, we can pass execution non null case only with:
Optional.ofNullable(nullableUsers)
.ifPresent(users -> users.forEach(user -> {
// work with user
}));
Nullable optional is also works very well with nested null references, e.g. we have some structure:
class User {
@Getter
Address address;
}
class Address {
@Getter
String street;
}
then instead of writing
if (user.getAddress() != null && user.getAddress().getStreet() != null) {
// work with street
}
we can use Optional:
Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getStreet)
.ifPresent(street -> {
// work with street
});