-1
HashMap<Long, Double> map = new HashMap<>();
// here init map, add some values there

// with 'foreach' all elements are printed
map.entrySet().stream().foreach(System.out::println);

// but when I use 'peek' nothing happens
map.entrySet().stream().peek(System.out::println);

My question is: why peek does not iterate all elements from the stream?

Balconsky
  • 2,234
  • 3
  • 26
  • 39
  • You may also want to look at https://stackoverflow.com/questions/47688418/what-is-the-difference-between-intermediate-and-terminal-operations – sfiss Nov 12 '19 at 14:18

1 Answers1

3

peek is an intermediate Stream operation, and therefore it is lazily evaluated.

Your pipeline has no terminal operation, so peek is never evaluated.

If you add a terminal operation, such as collect(Collectors.toList()), peek will be executed for all the elements required to perform the terminal operation, which in this example happens to be all the elements of the Stream:

map.entrySet().stream().peek(System.out::println).collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768