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.

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:

Sources (0)
See inline citations in the answer above.