Java.Java8.How can I get the average of all numbers?

✅ Example: Average of All Numbers in a Set

import java.util.Set;

public class AverageExample {
    public static void main(String[] args) {
        Set<Integer> numbers = Set.of(10, 20, 30, 40, 50);

        double average = numbers.stream()
                                .mapToInt(Integer::intValue)
                                .average()
                                .orElse(0.0); // fallback if set is empty

        System.out.println("Average: " + average);
    }
}

🔹 Output:

Average: 30.0

✅ Key Methods

MethodPurpose
mapToInt()Converts Stream<Integer> to IntStream
average()Returns an OptionalDouble
orElse(0.0)Returns 0.0 if the stream is empty

⚠️ Why orElse(0.0)?

Because .average() returns an OptionalDouble, and if the input is empty, we need to provide a default value to avoid exceptions.


🧠 Bonus: Using .ifPresent()

numbers.stream()
       .mapToInt(Integer::intValue)
       .average()
       .ifPresent(avg -> System.out.println("Average: " + avg));
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.