Java how to use stream map to return boolean [duplicate]

强颜欢笑 提交于 2020-12-26 06:45:06

问题


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

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


回答1:


you are using the stream wrong...

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



回答2:


It looks like helpFunction(item) returns some instance of some class that has a boolean status() method, and you want your method to return true if helpFunction(item).status() is true for any element of your Stream.

You can implement this logic with anyMatch:

public boolean status(List<String> myArray) {
    return myArray.stream()
                  .anyMatch(item -> helpFunction(item).status());
}


来源:https://stackoverflow.com/questions/47746443/java-how-to-use-stream-map-to-return-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!