typestar

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

  1. filter keeps what the predicate accepts; map transforms.
  2. toList materializes; limit stops early.
  3. Streams are lazy: findFirst stops at the first match.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Streams, step 22 of 29 in Language basics.

← Previous Next →