Why Is This Java Stream Not Filtering Correctly?

Profile Picture

Henrique Sa

OP
Admin
@riquelds.bsky.social
3 days ago

The stream should remove odd numbers, but it outputs all numbers unchanged.

List<Integer> list = List.of(1, 2, 3, 4, 5);

list.stream()
    .filter(n -> n % 2 == 0)
    .forEach(System.out::println);

But instead of printing 2 and 4, it prints all 5 numbers. Why?

java oop collections