✅ 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
Method | Description |
---|---|
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);