GothamCityRises
GothamCityRises

Reputation: 2102

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

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?

Upvotes: 3

Views: 12610

Answers (4)

Martin van Wingerden
Martin van Wingerden

Reputation: 981

If I read the question correctly the OP asks to split by '||' and is looking for the count, so a (minimal) viable solution would look like this:

import java.util.regex.Pattern;

class Scratch {
    public static void main(String[] args) {
        String test = "||a||a||b||a||bn";

        long count = Pattern.compile("\\|\\|")
                .splitAsStream(test)
                .filter(Scratch::isValid)
                .count();

        System.out.println(count);
    }

    private static boolean isValid(String r) {
        return "a".equals(r);
    }
}

Upvotes: 0

belbix
belbix

Reputation: 178

I hope this is what you want

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

Upvotes: 0

Amit Bera
Amit Bera

Reputation: 7235

If you want just count then you can use simple Stream#count

long count = Arrays.stream(range.split("\\s+"))
                       .map(r -> isValid(r))
                       .filter(b -> b)
                       .count();

And Since there no BooleanSteram like IntStream, DoubleStream etc,so you cann't convert Stream<Boolean> to boolean[], in that case, you have to use Boolean[]

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

Upvotes: 0

Andronicus
Andronicus

Reputation: 26056

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.

Upvotes: 2

Related Questions