I have list for each element I would like to do this(using Java 8):
disabledUsersOnLDAP.stream().forEach(user ->usersRepository.findEnabledByUsername(user.getUserName()).setEnabled(false));
How ever usersRepository.findEnabledByUsername
might return null's. Of course I can do this instead:
disabledUsersOnLDAP.stream().forEach(user -> {
UserEntity userEntity = usersRepository.findEnabledByUsername(user.getUserName());
{
if (userEntity != null) {
userEntity.setEnabled(false);
}
}
});
But I wonder if I could do the null check inline(in the first option)?
Some alternatives to the @assylias answser.
Use a method reference to Objects==nonNull for the
null
check:if you can update
UserEntity
with adisable
methodyou can again use a method reference (
UserEntity::disable
) :Some resources:
You could do a mapping + filtering before running the
forEach
part, which also makes it a bit more readable:Or as an alternative: