To find the sum of all the elements of an ArrayList
in Java 8, you can use the stream
API and the sum
method.
Here's an example of how to find the sum of all the elements of an ArrayList
of Integer
objects using the stream
API:
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 also use the reduce
method of the IntStream
class to find the sum of all 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).reduce(0, (a, b) -> a + b); System.out.println(sum); // prints 15
In this example, we're using the reduce
method to apply a binary operator to the elements of the stream, starting with an initial value of 0. The binary operator adds the two operands together, resulting in the sum of all 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.