Java如何使用流图返回布尔值 [英] Java how to use stream map to return boolean

查看:93
本文介绍了Java如何使用流图返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为结果返回布尔值.

I am trying to return a boolean for the result.

 public boolean status(List<String> myArray) {
      boolean statusOk = false;
      myArray.stream().forEach(item -> {
         helpFunction(item).map ( x -> {
              statusOk = x.status(); // x.status() returns a boolean
              if (x.status()) { 
                  return true;
              } 
              return false;
          });
      });
}

在lambda表达式中使用的抱怨变量应该是final或有效的final. 如果我分配statusOk,则无法在循环内分配.如何使用stream()和map()返回布尔变量?

It's complaining variable used in lambda expression should be final or effectively final. If I assign statusOk, then I couldn't assign inside the loop. How can I return a boolean variable using stream() and map()?

推荐答案

您使用的流错误...

you are using the stream wrong...

您不需要在流上执行foreach,只需调用

you dont need to do a foreach on the stream, invoke the anyMatch instead

public boolean status(List<String> myArray) {
      return myArray.stream().anyMatch(item -> here the logic related to x.status());
}

这篇关于Java如何使用流图返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆