java · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Where does reduce start? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> goals = List.of(2, 0, 3);
List<Integer> empty = List.of();
int total = goals.stream().reduce(10, (a, b) -> a + b);
int none = empty.stream().reduce(0, (a, b) -> a + b);
System.out.println(total + " " + none);
}
}
your turn
Your turn. Count the sevens.
On line 5, keep only the numbers that divide by 7 with nothing left over. % gives the remainder.
output
press run to see what happens
fix it
A 16-year-old got into the gig. Can you fix it?
output
press run to see what happens
- One guest is 16, yet everyone gets in. Which method asks the question on line 5?
anyMatchis happy when one item passes. Here every item has to pass.- Change
anyMatchtoallMatchon line 5, then run.
nailed it
you can sum, count and check in one line. :D
mapToIntgives anIntStreamwithsumandcount.reducefolds everything into one answer from a start value.anyMatchneeds one match;allMatchneeds them all.
new words in your collection
- IntStream
- reduce
- anyMatch
This lesson isn’t saved. A free account remembers every lesson you finish.