Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering avoiding unexpected null using lambda's inline

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.

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

like image 263
rayman Avatar asked Jul 16 '14 11:07

rayman


1 Answers

You could do a mapping + filtering before running the forEach part, which also makes it a bit more readable:

disabledUsersOnLDAP.stream()
            .map(user -> usersRepository.findEnabledByUsername(user.getUserName()))
            .filter(userEntity -> userEntity != null)
            .forEach(userEntity -> userEntity.setEnabled(false));

Or as an alternative:

disabledUsersOnLDAP.stream()
            .map(User::getUsername)
            .map(usersRepository::findEnabledByUsername)
            .filter(Objects::nonNull)
            .forEach(userEntity -> userEntity.setEnabled(false));
like image 70
assylias Avatar answered Sep 23 '22 18:09

assylias