Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of count here at the end of stream Java 8

I am a little bit confused about the utility of using count() here in this code :

Stream.iterate(1, (Integer n) -> n + 1)
    .peek(n -> System.out.println("number generated  - " + n))
    .filter(n -> (n % 2 == 0))
    .peek(n -> System.out
    .println("Even number filter passed for  –" + n))
    .limit(5).count();

With count() added to the end of the stream, i get what i want, which is to show this result :

number generated - 1 number generated - 2 Even number filter passed for –2 number generated - 3 number generated - 4 Even number filter passed for –4 number generated - 5 number generated - 6 Even number filter passed for –6 number generated - 7 number generated - 8 Even number filter passed for –8 number generated - 9 number generated - 10 Even number filter passed for –10

but if i delete count() from the end of the stream statement i didn't get any result.

like image 593
Issam Bakrim Avatar asked Mar 07 '23 12:03

Issam Bakrim


1 Answers

You need to perform a terminal operation on the stream for anything to happen. If you drop the .count() the stream basically does nothing. Think about the method peek and filter and so on to just take in a function and putting it on an internal queue of functions to execute.
The remembered functions will only be executed after you use one terminal operation after which you no longer have a stream but some result or nothing at all. count, collect, reduce, forEach are such terminal operations.

Read more about it in the "Stream operations and pipelines" section of the docs and take a look through the functions in the Stream docs to see which methods are terminal and which are not.

like image 185
luk2302 Avatar answered Apr 25 '23 02:04

luk2302