[英]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)
.并计算结果数组中有多少元素为函数boolean isValid(String[] r)
返回true
。
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.我正在尝试使用Arrays.stream
来评估和过滤数组,最后,过滤结果数组以仅保留真实值。
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.代替_whatGoesHere
,我尝试放置b
, b == true
,但无济于事。 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:你可以简单地传递它自己,lambda 看起来像b -> b
(因为它已经是一个布尔值:
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.但是你只得到值,这些值是true
,并将它们打包到数组中——这将产生一个只有true
值的布尔数组。 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
. PS:要计算值,您可以使用Stream#count
。
If you want just count then you can use simple Stream#count
如果你只想计数,那么你可以使用简单的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[]
并且由于没有像IntStream, DoubleStream
等的IntStream, DoubleStream
所以你不能将Stream<Boolean> to boolean[]
转换Stream<Boolean> to boolean[]
,在这种情况下,你必须使用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 '||'如果我正确阅读了问题,OP 会要求以“||”分割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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.