Stream is a new feature added to java8 that allows elements in a collection to be called in a pipelined fashion. If only the method calls Stream’s method as its return type. It’s a superficial assembly line, not black technology. Compare the expected results of the following code with the actual results.

Stream<String> strs = Stream.generate(() -> "A").limit(3);
strs.map(s -> {
    System.out.println("map1");
    return s + "A";
}).map(s -> {
    System.out.println("map2");
    return s + "A";
}).map(s -> {
    System.out.println("map3");
    return s + "A";
}).forEach(System.out::println);
Copy the code


Stream

map(Function
mapper). The map method is executed three times, each time returning a Stream object. Finally, the forEach method is called. The result should be

map1
map1
map1
map2
map2
map2
map3
map3
map3
AAAA
AAAA
AAAA
Copy the code

The actual results were surprising:

map1
map2
map3
AAAA
map1
map2
map3
AAAA
map1
map2
map3
AAAA
Copy the code

The Stream will be three timesmapCall and onceforEachThe call is optimized. Each time an element is iterated, three are executed at a timeThe map 'and onceThe forEach ` method.