java 不用if,用于if条件的Java Lambda表达式 - 这里不需要

Consider the case where an if condition needs to evaluate an array or a List. A simple example: check if all elements are true. But I'm looking for generic way to do it

Normally I'd do it like that:

boolean allTrue = true;

for (Boolean bool : bools){

if (!bool) {

allTrue = false;

break;

}

}

if (allTrue){

// do Something

}

But now I'd like to hide it into my if condition. I tried using Lambda Expressions for this, but it's not working:

if (() -> {

for (Boolean bool : bools)

if (!bool)

return false;

return true;

}){

// do something

}

If this were working I could do something more complicated like

if (() -> {

int number = 0;

for (MyObject myobject : myobjects)

if (myObject.getNumber() != 0)

numbers++;

if (numbers > 2)

return false;

return true;

}{

//do something

}

Is there a better way to do it is it just a syntax error?

UPDATE

I'm not talking about the boolean array, rather looking for a generic way to achieve that.

解决方案

You can write, given for instance a List:

if (!list.stream().allMatch(x -> x)) {

// not every member is true

}

Or:

if (list.stream().anyMatch(x -> !x)) {

// at least one member is false

}

If you have an array of booleans, then use Arrays.stream() to obtain a stream out of it instead.

More generally, for a Stream providing elements of (generic) type X, you have to provide a Predicate super X> to .{all,any}Match() (either a "full" predicate, or a lambda, or a method reference -- many things go). The return value of these methods are self explanatory -- I think.

Now, to count elements which obey a certain predicate, you have .count(), which you can combine with .filter() -- which also takes (whatever is) a Predicate as an argument. For instance checking if you have more than 2 elements in a List whose length is greater than 5 you'd do:

if (list.stream().filter(s -> s.length() > 5).count() > 2L) {

// Yup...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值