Filter & map in Java
Transform collections without writing a loop.
import java.util.List;
var numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
var evens = numbers.stream().filter(n -> n % 2 == 0).toList();
System.out.println(evens);
var squares = numbers.stream().map(n -> n * n).limit(4).toList();
System.out.println(squares);
// streams are lazy: nothing runs until a terminal operation asks
var firstBig = numbers.stream().map(n -> n * n)
.filter(sq -> sq > 20).findFirst();
System.out.println(firstBig.orElse(-1));
How it works
filterkeeps what the predicate accepts;maptransforms.toListmaterializes;limitstops early.- Streams are lazy:
findFirststops at the first match.
Keywords and builtins used here
var
The run, in numbers
- Lines
- 14
- Characters to type
- 456
- Tokens
- 152
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 101 seconds.
Step 1 of 3 in Streams, step 22 of 29 in Language basics.