Java 使用 lambda 的内联过滤避免意外空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24779806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:49:29  来源:igfitidea点击:

Filtering avoiding unexpected null using lambda's inline

javalambdajava-8

提问by rayman

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

我有我想要执行此操作的每个元素的列表(使用 Java 8):

disabledUsersOnLDAP.stream().forEach(user ->usersRepository.findEnabledByUsername(user.getUserName()).setEnabled(false));

How ever usersRepository.findEnabledByUsernamemight return null's. Of course I can do this instead:

怎么usersRepository.findEnabledByUsername可能返回空值。当然,我可以这样做:

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

但我想知道我是否可以内联进行空检查(在第一个选项中)?

采纳答案by assylias

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

您可以在运行forEach部件之前进行映射 + 过滤,这也使其更具可读性:

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

回答by gontard

Some alternatives to the @assylias answser.

@assylias answser 的一些替代品。

Use a method reference to Objects==nonNullfor the nullcheck:

使用方法参照对象==非空null检查:

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


if you can update UserEntitywith a disablemethod

如果你可以UserEntity用一种disable方法 更新

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

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

您可以再次使用方法引用 ( UserEntity::disable):

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


Some resources:

一些资源: