Java and Spring Level 1 This level · 39 of 105
Easy java streams

Salary sum and average

The 30 second answer

I use summarizingDouble so sum, average, count, min, and max all come from one pass. Floating-point sums can drift with order or parallelism, so for money I switch to a BigDecimal reduce instead of double.

Could you say this in an interview?
DoubleSummaryStatistics s = emps.stream()
    .collect(Collectors.summarizingDouble(Employee::salary));
s.getSum();
s.getAverage();

One pass. Floating-point sum can differ by encounter order or parallelism.

[Opinion] For money use BigDecimal with reduce(BigDecimal.ZERO, BigDecimal::add).

Alternate interview scenarios

"Sum the squares of the even numbers in a list of integers."

Filter, square on a primitive stream, sum:

var nums = List.of(1, 2, 3, 4, -6, 50_000);
long sumOfEvenSquares = nums.stream()
    .filter(n -> n % 2 == 0)
    .mapToLong(n -> (long) n * n)
    .sum();
// 2500000056

Two points make this answer stand out. First, mapToInt(n -> n * n).sum() overflows silently: Java integer arithmetic keeps only the low-order bits, and 50,000 squared is already outside the int range, so the int sum of this list comes out negative. Widening to long before multiplying avoids it. Second, test evenness with n % 2 == 0 and oddness with n % 2 != 0, never n % 2 == 1. In Java the remainder takes the sign of the dividend, so -3 % 2 is -1 and negative odd numbers would be missed. The plain sum and average of a list of integers follow the same shape: mapToInt(Integer::intValue).sum() and .average(), which returns OptionalDouble.

Sources (4)
  1. Collectors.summarizingDoubledocs.oracle.com
  2. DoubleSummaryStatisticsdocs.oracle.com
  3. IntStream (sum, average)docs.oracle.com
  4. JLS 15.17 Multiplicative operators (overflow, remainder sign)docs.oracle.com
Previous
Next