Approach 1: Using mapToInt()
and average()
List<Integer> nums = Arrays.asList(1, 2, 3, 4); double avg = nums.stream() .mapToInt(Integer::intValue) .average() .orElse(0.0); System.out.println(avg); // 2.5
Why it works:
IntStream.average()
returns anOptionalDouble
.orElse
provides a default if the list is empty.
Approach 2: Using Collectors.averagingInt()
(Alternative)
double avg = nums.stream() .collect(Collectors.averagingInt(Integer::intValue)); System.out.println(avg); // 2.5
Why it works:
- Collector handles the aggregation automatically.
- More readable for aggregations in streams.