java - 错误 : incompatible types: unexpected return value : Java 8

标签 java foreach java-8 java-stream

<分区>

我写了一个返回 boolean 值的简单方法。

private boolean isActionAvailable(Collection<StudentConfiguration> studentConfigs){
       if(studentConfigs != null)
        {
            studentConfigs.forEach(studentConfig -> {
                if(studentConfig.action() == null || !studentConfig.action().equals(Action.DELETE)) {
                    return true;
                }
            });
        }
        return false;
    }

该方法抛出以下异常。

error: incompatible types: unexpected return value
            studentConfigs.forEach(studentConfig -> 

我的代码有什么问题?

最佳答案

传递给 forEach 的 lambda 表达式不应有返回值。

如果输入 Collection 的任何元素满足条件,您似乎想要返回 true:

private boolean isActionAvailable(Collection<StudentConfiguration> studentConfigs){
    if(studentConfigs != null) {
        if (studentConfigs.stream().anyMatch(sc -> sc.action() == null || !sc.action().equals(Action.DELETE))) {
            return true;
        }
    }
    return false;
}

正如 Holger 所建议的,这可以简化为一条语句:

return studentConfigs != null && studentConfigs.stream().anyMatch(sc -> sc.action() == null || !sc.action().equals(Action.DELETE));

return studentConfigs != null ? studentConfigs.stream().anyMatch(sc -> sc.action() == null || !sc.action().equals(Action.DELETE)) : false;

关于java - 错误 : incompatible types: unexpected return value : Java 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53480923/

相关文章:

java - ORMLite QueryBuilder.orderByRaw(String, SelectArg) 忽略 QueryBuilder.queryRaw() 上的 SelectArg

java - 用于检索最后执行的 SQL 语句的 DB2 系统运行时表

java - 部署在tomcat上的spring boot无法启动

php - Foreach 循环与 while 循环结果

由于 com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged,JavaFx 无法加载@font-face 字体

java - Selenium 未在表单中填写密码属性

c++ - 'for_each_n'不是C++ 17中 'std'的成员

mysql - 使用 wpdb 的嵌套查询

java-8 - 在 DIY openshift 上安装 JDK8

java - if-elseif-else 类似于 Java 8 流的功能