CKTIS / Java
Summing after filtering: mapToInt, mapToLong, and sum()
Map filtered objects to a primitive stream and sum its values. Choose `int` or `long` before summing based on the range the total needs.
Version: Java SE 21
Syntax
Stream<T>: IntStream mapToInt(ToIntFunction<? super T> mapper)
Stream<T>: LongStream mapToLong(ToLongFunction<? super T> mapper)
IntStream: int sum()
LongStream: long sum()If the condition depends on the object, put filter before the mapping step. The Stream.mapToInt/mapToLong distinction is the type of number the mapper produces: mapToInt takes a ToIntFunction<? super T> and maps each retained element to one int in an IntStream; mapToLong takes a ToLongFunction<? super T> and produces a LongStream of long values. Unlike map producing a Stream<Integer> or Stream<Long>, these methods do not box the mapped values.
Filtering and mapping are lazy intermediate operations: adding them does not itself process elements. IntStream.sum() is a no-argument terminal operation that triggers processing and returns an int; an empty stream yields 0. The corresponding LongStream.sum() returns a long, or 0L for an empty stream. After summing, create a fresh stream from the source if you need another pass.
If the total may exceed the int range but fits in long, use mapToLong(...).sum(). Assigning the result of IntStream.sum() to a long widens it only after the int addition, so it cannot undo overflow. Addition in either type can overflow without throwing an exception.
Examples
import java.util.List;
public class Main {
record Sale(boolean confirmed, int cents) {}
public static void main(String[] args) {
var sales = List.of(new Sale(true, 120), new Sale(false, 900), new Sale(true, 80));
int totalCents = sales.stream()
.filter(Sale::confirmed)
.mapToInt(Sale::cents)
.sum();
System.out.println(totalCents);
}
}Result
200
`filter` keeps only confirmed sales. `mapToInt` extracts their amounts in cents, and `sum()` gives `120 + 80 = 200`. The `900` is not added.
Related lessons
- Java · Lesson 48 · Advanced · Version: 2