Java.Java8.How can I get the sum of all numbers in a set?

✅ Example: Sum of All Numbers in a Set

import java.util.Set;

public class SumOfSet {
    public static void main(String[] args) {
        Set<Integer> numbers = Set.of(10, 25, 7, 40, 18);

        int sum = numbers.stream()
                         .mapToInt(Integer::intValue) // convert to IntStream
                         .sum();                      // sum up the values

        System.out.println("Sum: " + sum);
    }
}

🔹 Output:

Sum: 100

✅ Breakdown

MethodDescription
stream()Turns the Set into a Stream
mapToInt()Converts Integer objects to primitives
sum()Sums all elements in the IntStream

🧠 Bonus: Using reduce()

If you want to practice reduce():

int sum = numbers.stream()
                 .reduce(0, Integer::sum);
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.