简体   繁体   中英

How does anyMatch work in java stream in this example

This is my code:

Stream.of("d2", "a2", "b1", "b3", "c")
                .map(s -> {
                    System.out.println("map: " + s);
                    return s.toUpperCase();
                })
                .anyMatch(s -> {
                    System.out.println("anyMatch: " + s);
                    return ((String) s).startsWith("A");
                });

The output is:

map: d2
anyMatch: D2
map: a2
anyMatch: A2

My question is how come the first element entered the stream while the 3rd, and 4th did not?

Any detailed explanation is appreciated.

From the text of the javadoc :

Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

It's a short circuit operation that results in true upon encountering that element.

Use forEach if you want to process each item.

You code is equivalent to:

for (String s : new String[] {"d2", "a2", "b1", "b3", "c"}) {
    System.out.println("map: " + s);
    s = s.toUpperCase();
    System.out.println("anyMatch: " + s);
    if (((String) s).startsWith("A"))
        break;
}

The elements after "a2" are not processed because of the break statement. This is called short-circuiting , ie it breaks the loop (the circuit ) before reaching the end (stops short of the end).

The anyMatch(...) method is documented to be short-circuiting :

This is a short-circuiting terminal operation .

The link leads to this explanation:

Further, some operations are deemed short-circuiting operations. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time. Having a short-circuiting operation in the pipeline is a necessary, but not sufficient, condition for the processing of an infinite stream to terminate normally in finite time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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