用于if条件的Java Lambda表达式 - 这里不需要 [英] Java Lambda Expression for if condition - not expected here

查看:1416
本文介绍了用于if条件的Java Lambda表达式 - 这里不需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑if条件需要评估数组或List的情况。一个简单的例子:检查所有元素是否都为真。但我正在寻找通用方式来做这件事

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

通常我会这样做:

boolean allTrue = true;
for (Boolean bool : bools){
    if (!bool) {
        allTrue = false;
        break;
     }
}
if (allTrue){
     // do Something
}

但现在我想把它隐藏到我的if条件中。我尝试使用Lambda Expressions,但它不起作用:

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
我不是在谈论布尔数组,而是寻找一种通用的方法来实现它。

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

推荐答案

你可以写一下,例如 List< Boole >

if (!list.stream().allMatch(x -> x)) {
    // not every member is true
}

或:

if (list.stream().anyMatch(x -> !x)) {
    // at least one member is false
}

如果你有一个数组 of booleans,然后使用 Arrays.stream()来获取它的流。

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

更一般地说,对于 Stream 提供(通用)类型的元素 X ,你必须提供 Predicate<?超级X> 。{all,any} Match()(完整谓词,或lambda或方法引用 - - 很多事情都去了)。这些方法的返回值是不言自明的 - 我认为。

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.

现在, count 服从某个谓词的元素,你有 .count(),你可以与 .filter()结合使用 - 谓词作为参数。例如,检查你的长度大于5的 List< String> 中是否有超过2个元素:

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<String> whose length is greater than 5 you'd do:

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

这篇关于用于if条件的Java Lambda表达式 - 这里不需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆