简体   繁体   中英

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?

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM