To sum the elements of an ArrayList
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 sum the elements of an ArrayList
of Integer
objects:
ArrayList<Integer> list = new ArrayList<>(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 sum the elements of an ArrayList
. Here's an example of how to do this:
ArrayList<Integer> list = new ArrayList<>(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.