streams
List<Integer> nums = List.of(2, 5, 8);
List<Integer> even = nums.stream()
.filter(n -> n % 2 == 0)
.toList();
Output:
[2, 8]
What a stream is
A stream is a pipeline over a source It does not store data It describes how data moves
Intermediate and terminal
filter , map , sorted are intermediate
They return a new stream
toList , forEach , collect are terminal
Nothing runs until a terminal operation exists
Why it matters
The code reads like the question That is not cosmetic, it reduces the chance of an off by one error in the loop index
When not to use it
- tight loops where allocation overhead matters
- debugging, where a plain loop is easier to inspect
- code that needs indexed access during the pass
Next
Concurrency in 09 concurrency
Posted