How to use a lambda to filter a boolean array in Java

GothamCityRises :

I want to split a string by "||" and count how many elements from the resulting array return true for a function boolean isValid(String[] r).

I'm trying to use Arrays.stream to evaluate and filter the array, and finally, filter the resulting array to only keep the true values.

boolean[] truthSet = Arrays.stream(range.split("\\s+))
                           .map(r -> isValid(r))
                           .filter(b -> _whatGoesHere_)
                           .toArray(boolean[]::new);

In place of _whatGoesHere, I tried putting b, b == true, to no avail. What's the right way to achieve this?

Andronicus :

You can simply pass itself, the lambda would look like b -> b (because it's already a boolean:

 Boolean[] truthSet = Arrays.stream(range.split("\\s+"))
                       .map(r -> isValid(r))
                       .filter(b -> b)
                       .toArray(Boolean[]::new);

But you're getting only values, that are true and packing them to array - this will produce a boolean array with nothing but true values. Maybe you meant:

 String[] validStrings = Arrays.stream(range.split("\\s+"))
                       .filter(r -> isValid(r))
                       .toArray(String[]::new);

P.S.: To count the values, you can use Stream#count.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141366&siteId=1