×

java · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An knows how to do sums.

A Stream<Integer> holds Integer objects and has no sum. Switch with mapToInt, which gives an IntStream of plain int values, and the maths methods appear: sum() and count(). IntStream.rangeClosed(1, 5) makes the numbers 1 to 5 from nothing.

For any other way of combining, use . reduce(1, (a, b) -> a * b) starts at 1 and multiplies each item in. The start value is also the answer for an empty stream, so choose one that changes nothing.

and allMatch answer yes-or-no questions about the whole stream. They stop early: anyMatch quits at the first match, so even huge streams can finish fast.

import java.util.List;
import java.util.stream.IntStream;
public class Main {
    public static void main(String[] args) {
        List<String> basket = List.of("bread:120", "milk:95", "eggs:210");
        int pence = basket.stream()
            .mapToInt(item -> Integer.parseInt(item.split(":")[1]))
            .sum();
        System.out.println("Total: " + pence + "p");
        System.out.println(IntStream.rangeClosed(1, 5).reduce(1, (a, b) -> a * b));
        System.out.println(basket.stream().anyMatch(item -> item.startsWith("milk")));
        System.out.println(basket.stream().count());
    }
}

count() answers with a long, a whole number type with far more room than int.