Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 598
user3784773 Avatar asked Dec 11 '17 04:12

user3784773


People also ask

How do I find duplicates in stream?

For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.

What does Stream Map return in Java?

Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation.

How do you return a boolean in lambda expression?

Consider lambda expression account -> true . The compiler verifies that the lambda matches Predicate<T> 's boolean test(T) method, which it does--the lambda presents a single parameter ( account ) and its body always returns a Boolean value ( true ). For this lambda, test() is implemented to execute return true; .


2 Answers

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());
}
like image 155
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 05 '22 02:10

ΦXocę 웃 Пepeúpa ツ


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());
}
like image 33
Eran Avatar answered Oct 05 '22 00:10

Eran