Start learning free

LESSON 266 OF 671 · RECORDS, SORTING & BUILT-INS

Map and Filter in Java

Lesson

TL ; DR:

Call stream() on a list. Then map changes every item, or filter keeps only the items that pass a test. At the end, toList() collects the result in a new list.


List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));

List<Integer> squares = nums.stream().map(n -> n * n).toList();
// [1, 4, 9, 16]

List<Integer> evens = nums.stream().filter(n -> n % 2 == 0).toList();
// [2, 4]

List<Integer> big = nums.stream().filter(n -> n > 2).map(n -> n * 10).toList();
// [30, 40]


Full lesson:

You often build a new list from an old one. You already know how to do it with a loop:

List<Integer> squares = new ArrayList<>();

for (int n : nums) {
    squares.add(n * n);
}

A stream does the same in one line. First, nums.stream() hands over the items one at a time. Then map changes every item with a lambda, like the one you gave sort in Custom Sorting. At the end, toList() collects the results in a new list.

List<Integer> squares = nums.stream().map(n -> n * n).toList();

This lambda gets only one value. Read n -> n * n as: take n, give back n * n.

filter takes a lambda that gives true or false. It keeps only the items that get true.

List<Integer> evens = nums.stream().filter(n -> n % 2 == 0).toList();

You can chain the two. First filter picks the items, then map changes them.

List<Integer> big = nums.stream().filter(n -> n > 2).map(n -> n * 10).toList();
// [30, 40]

The stream makes a new list. The old list, nums, stays as it was.

Watch out: a list has no map of its own, so call stream() first. Also, the list from toList() can't change. Calling add on it stops the program with an error.


Your task

A theater keeps the price of one ticket for each show in prices. Build doubled with a stream and map: the price of two tickets for each show.

A quiz keeps its scores in scores. A score of 50 or more passes. Build passed with a stream and filter: only the passing scores.

The code already prints both lists, one value per line.

Expected output:

Two tickets cost 24
Two tickets cost 16
Two tickets cost 30
72 passed
50 passed
90 passed
STEP 1 OF 2
    Ctrl + Enter to check