To find the sum of the numbers in a list in Java, you can iterate over the elements of the list and add them together using a loop.
Here's an example of how to find the sum of the numbers in a List
of Integer
objects using a loop:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); int sum = 0; for (int i : list) { sum += i; } System.out.println(sum); // prints 15
In this example, we're using a for-each loop to iterate over the elements of the list
and add them to the sum
variable. The output will be the sum of the elements of the list: 15.
You can also use the stream
API introduced in Java 8 to find the sum of the numbers in a list. Here's an example of how to do this:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); int sum = list.stream().mapToInt(i -> i).sum(); System.out.println(sum); // prints 15
In this example, we're using the stream
method to create a stream of Integer
objects, the mapToInt
method to convert the stream to an IntStream
, and the sum
method to sum the elements of the stream.
You can find more information about the stream
API and examples of how to use it in the Java documentation.