There is the following List<String> :

 List<String> arrList = Arrays.asList("небо", "земля", "облако", "космос", "звезда", "галактика"); 

Having created a stream , we filter the elements (words) with a length of less than 6 characters, for example, and count the number of these elements.

 long count = arrList.stream().filter(w -> w.length() > 6).count(); 

In what order are the filter() and count() operations actually performed? In the same in which they follow in this expression?

  • Flows are lazy (lazy) - this is the first thing you need to learn when working with them. Operations will not be performed at all until you call the collector method. - Nofate

2 answers 2

The order of operations on the stream does not change . But it should be borne in mind that operations are divided into two types:

  • intermediate ( intermediate ), for example, filter, skip, peek , etc. They somehow change the input stream.
  • terminal operations such as count, forEach , etc. These operations have some kind of result or side effect.

The difference between the first and second types is in runtime. Those. intermediate operations are lazy , and they will be calculated only after further calling the final operation.

More details here .

    The order of streaming operations does not correspond to the order in which they (operations) are called in I / O streams. First, the first element is requested in the count() method, then in the filter() method, the element is queried until an element is found that is less than 6 letters long.

    Source: Kay S. Horstmann - Java SE 8. Introductory Course

    • This description is too specific and not entirely correct in general. - Nofate
    • @Nofate: thanks for the remark, informative - TimurVI February