To get the sum of a list of integers in Java, you can use a for loop to iterate through the list and add each element to a running total. Here's an example of how you could do this:
import java.util.List; List<Integer> numbers = List.of(1, 2, 3, 4, 5); int sum = 0; for (int number : numbers) { sum += number; } System.out.println("The sum is: " + sum);
This code will output "The sum is: 15".
Alternatively, you can use the IntStream.sum()
method from the Java Stream API to calculate the sum of the elements in the list. Here's an example of how you could use this method:
import java.util.List; import java.util.stream.IntStream; List<Integer> numbers = List.of(1, 2, 3, 4, 5); int sum = IntStream.of(numbers).sum(); System.out.println("The sum is: " + sum);
This code will also output "The sum is: 15".
Note that the IntStream.sum()
method only works for lists of integers. If you are using a list of a different type, such as Double
or Long
, you will need to use a different method or write your own code to calculate the sum.