J.IV · Java 25 practice question
What does the following Java 25 program print using Stream and IntStream aggregate operations?
import java.util.List;
record Widget(String color, int weight) {}
void main() {
List<Widget> widgets = List.of(
new Widget("RED", 10),
new Widget("BLUE", 25),
new Widget("RED", 15)
);
int sum = widgets.stream()
.filter(w -> w.color().equals("RED"))
.mapToInt(Widget::weight)
.sum();
IO.println(sum);
}
Check answer and explanation
Correct answer: 25
Explanation
The pipeline filters for RED widgets (weights 10 and 15), converts them to an IntStream with mapToInt, and sums them to produce 25.
Common trap
50 is the total weight of all widgets including the BLUE widget that filter() removes. 10 is only the weight of the first RED widget rather than the sum of all matching widgets.
Source: Java SE 25 API: Stream
Checked against the cited text on 2026-11-25.