Java Streams learning path Level 1 This level ยท 21 of 25
Easy java streams

Employees earning above average salary

The 30 second answer

I compute the average on a DoubleStream first, then open a second stream from the list and filter above that average. One stream cannot be traversed twice, so the two-pass shape is required. For real money I would use BigDecimal, not double.

Could you say this in an interview?
double avg = emps.stream()
    .mapToDouble(Employee::salary)
    .average()
    .orElse(0);

List<Employee> above = emps.stream()
    .filter(e -> e.salary() > avg)
    .toList();

Needs two passes โ€” a stream cannot be traversed twice, so open a new one from the source. average() returns OptionalDouble. Stream.toList() (Java 16+) returns an unmodifiable list.

[Opinion] For production money amounts, use BigDecimal, not double.

Sources (2)
  1. DoubleStream.averagedocs.oracle.com
  2. Stream.toListdocs.oracle.com
Previous
Next