Java Lambda expressions forEach can not jump out of the cycle of Solutions

Java Lambda expressions forEach can not jump out of the cycle of Solutions

If you used the forEach method to traverse the collection, you will find return in lambda expression does not terminate the loop, which is due to the realization of the underlying cause of lambda, look at the following example:

public static void main(String[] args) {
    List<String> list = Lists.newArrayList();
    list.add("a");
    list.add("b");
    list.add("c");

    list.forEach(s -> {
        System.out.println("s = " + s);
        if (s.equals("b")) {
            return;
        }
    });
}
//返回结果:
//s = a
//s = b
//s = c

You can see the forEach method that is adopted return, circulation still continues, that there is any way out of the cycle of it?

The method can throw an exception:

public static void main(String[] args) {
    List<String> list = Lists.newArrayList();
    list.add("a");
    list.add("b");
    list.add("c");

    try {
        list.forEach(s -> {
            System.out.println("s = " + s);
            if (s.equals("b")) {
                throw new RuntimeException();
            }
        });
    }catch (Exception e){}
}
//返回结果:
//s = a
//s = b

But think about it, so too frustrated, in fact, you can put it another thought, out of the premise is certainly satisfies certain conditions, you can use anyMatch () method:

AnyMatch () receiving in return a value of type boolean expression returns true as long as the cycle is terminated, so that the business logic can be written in the determination result before returning.

public static void main(String[] args) {
    List<String> list = Lists.newArrayList();
    list.add("a");
    list.add("b");
    list.add("c");

    list.stream().anyMatch(s -> {
        System.out.println("do something");
        System.out.println("s=" + s);
        return s.equals("b");
    });
}
// do something
// s=a
// do something
// s=b

Similarly, the use of similar ideas you can use filter () method, the idea is the same, which means stop when the condition findAny just find satisfying.

public static void main(String[] args) {
    List<String> list = Lists.newArrayList();
    list.add("a");
    list.add("b");
    list.add("c");

    list.stream().filter(s -> {
        System.out.println("s=" + s);
        return s.equals("b");
    }).findAny();
}
//返回结果:
//s = a
//s = b

Guess you like

Origin www.cnblogs.com/keeya/p/11306254.html