简体   繁体   English

Java 8 lambda stream

[英]Java 8 lambda stream

I am trying to do the following but it throws error.我正在尝试执行以下操作,但它会引发错误。 Iterate over the list and call another method passing item as parameter and return true if it matches the condition.遍历列表并调用另一个方法,将 item 作为参数传递,如果它与条件匹配则返回 true。

I have below code:我有以下代码:

public boolean myMethod() {
    List<String> list1 = method1();
    list1.forEach(item1 -> {
        List<String> list2 = method2(item1);
        if(list2.stream().anyMatch(item2 -> ***item2 condition***)) {
           return true;
        }
    });
    return false;
}

but return statement is not allowed inside for each.但是每个内部都不允许返回语句。 How can I achieve this?我怎样才能做到这一点?

Use another anyMatch to "bring the return value outside":使用另一个anyMatch来“将返回值带到外面”:

return list1.stream().anyMatch(item1 -> {
    List<String> list2 = method2(item1);
    return list2.stream().anyMatch(item2 -> item2 condition);
});

Or more simply, use a flatMap :或者更简单地说,使用flatMap

return list1.stream().flatMap(item1 -> method2(item1).stream()).anyMatch(item2 -> item2 condition);

You can use takeWhile您可以使用 takeWhile

public static void main ( String [] args){
    System.out.println(check());
}

public static boolean check() {
    List<String> list1 = List.of("1", "2");
    var count = list1.stream().takeWhile(item1 -> {
        List<String> list2 = List.of("2", "3");
        return list2.stream().anyMatch(list2::contains);
    }).count();
    return count > 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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