Approach 1
import java.util.Arrays; import java.util.List; public class SumOfNumbers { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8); // Using Stream and mapToInt with sum() int sum = numbers.stream() .mapToInt(Integer::intValue) .sum(); System.out.println("Sum of all numbers: " + sum); } }
Approach 2
import java.util.Arrays; import java.util.List; public class SumUsingReduce { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(3, 5, 7, 2, 8); // Using reduce method int sum = numbers.stream() .reduce(0, (a, b) -> a + b); System.out.println("Sum of all numbers: " + sum); } }