Filtering avoiding unexpected null using lambda's inline

前端 未结 2 735
眼角桃花
眼角桃花 2021-02-12 21:39

I have list for each element I would like to do this (using Java 8):

disabledUsersOnLDAP.stream().forEach(user -> usersRepository
                .findEnabledB         


        
相关标签:
2条回答
  • 2021-02-12 21:59

    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));
    
    0 讨论(0)
  • 2021-02-12 21:59

    Some alternatives to the @assylias answser.

    Use a method reference to Objects==nonNull for the null check:

    disabledUsersOnLDAP.stream()
        .map(User::getUsername)
        .map(usersRepository::findEnabledByUsername)
        .filter(Objects::nonNull)
        .forEach(userEntity -> userEntity.setEnabled(false));
    

    if you can update UserEntity with a disable method

    class UserEntity {
        public void disable() {
            setEnabled(false);
        }
    }
    

    you can again use a method reference (UserEntity::disable) :

    disabledUsersOnLDAP.stream()
        .map(User::getUsername)
        .map(usersRepository::findEnabledByUsername)
        .filter(Objects::nonNull)
        .forEach(UserEntity::disable);
    

    Some resources:

    • Method References on the java tutorial
    • JSR 335: Lambda Expressions for the JavaTM Programming Language
    0 讨论(0)
提交回复
热议问题