I learned another thing about java streams today. ...
# ask-ai
c
I learned another thing about java streams today. Anyone want to guess what this code snippet prints out? I'll put the answer in the thread, so don't open the thread if you want to puzzle about it first.
Copy code
public static void main(String[] args) {
    final List<Integer> integers = List.of(1, 2, 3, 4);

    final long count = integers
        .stream()
        .peek(i -> System.out.println("i = " + i))
        .count();
    System.out.println("count = " + count);
  }
🙌 1
The answer is it prints just (the value stored in the count variable):
Copy code
count = 4
I had expected it to print:
Copy code
i = 1
i = 2
i = 3
i = 4
count = 4
the block in peek is never executed.
and so if you have the filter in there it does print. e.g.
Copy code
public static void main(String[] args) {
  final List<Integer> integers = List.of(1, 2, 3, 4);
  final long count = integers
      .stream()
      .peek(i -> System.out.println("before filter i = " + i))
      .filter(i -> i < 5)
      .peek(i -> System.out.println("after filter i = " + i))
      .count();
  System.out.println("count = " + count);
}
outputs:
Copy code
before filter i = 1
after filter i = 1
before filter i = 2
after filter i = 2
before filter i = 3
after filter i = 3
before filter i = 4
after filter i = 4
count = 4
m
This is a confirmation that
streams
are not a good abstraction in java
r
Imagine not using
.reduce((a,b) -> a + 1)
to count.
🤣 2