Video in progress
What is the difference between IntStream and Stream<Integer>?
IntStream works with the primitive int: there's no boxing and it has numeric methods like sum(), average() and max(). Stream<Integer> wraps each number in an Integer object and doesn't have such methods.
📖 Answer
List<Order> orders = ...;
// IntStream: a direct sum
int total = orders.stream().mapToInt(Order::quantity).sum();
// Stream<Integer> has no sum(): you need reduce
int total2 = orders.stream().map(Order::quantity).reduce(0, Integer::sum);
Conversions:
Stream<T>→IntStream:mapToInt(...);IntStream→Stream<Integer>:boxed();IntStream→Stream<T>:mapToObj(...).
average() returns an OptionalDouble, because an empty stream has no average:
double avg = scores.stream().mapToInt(Integer::intValue).average().orElse(0);
If you need several statistics at once, use summaryStatistics(): it gives the min, max, average, sum and count in a single pass.
There are similar LongStream and DoubleStream too. For money amounts use long (in tiyin) or BigDecimal, not double.
Sign up to mark studied questions and save your progress.