How to sum up the elements of an Integer List by Java 7 VS Java 8 ?

Here in this example we are summing up the elements of a List of Integer by Java 7 and Java 8. In Java 7 it is very straight forward.

1.  We will take a variable total and set its initial value as 0.
2.  Then we will loop through the collection and add elements one by one with total.
3.  We are ready with the sum at the end of the iteration.

public static int sumInJava7(List numbers) {
  int total = 0;
  for (int number : numbers) {
	total += number;
  return total;

Now lets have some fun with Java 8. Java 8 has introduced some Aggregate Operations which we normally do with DB queries. One such operation is Stream.reduce method. It  is a general-purpose reduction operation. Consider the following pipeline, which calculates the sum of the elements in a List of Integers.

public static int sumInJava8(List numbers) {
  return // Convert collection to Stream
   .reduce(0, (total, number) -> total + number); // Sum elements with 0 as starting value

The reduce operation in this example takes two arguments:

identity : The identity element is both the initial value of the reduction and the default result if there are no elements in the stream. In this example, the identity element is 0; this is the initial value of the sum of the elements of the list and the default value if no members exist in the collection numbers.

accumulator : The accumulator function takes two parameters: a partial result of the reduction (in this example, the sum of all processed integers so far) and the next element of the stream (in this example, an integer). It returns a new partial result. In this example, the accumulator function is a lambda expression that adds two Integer values and returns an Integer value:

(total, number) -> total + number

The reduce operation always returns a new value. However, the accumulator function also returns a new value every time it processes an element of a stream. Suppose that you want to reduce the elements of a stream to a more complex object, such as a collection. This might hinder the performance of your application. If your reduce operation involves adding elements to a collection, then every time your accumulator function processes an element, it creates a new collection that includes the element, which is inefficient. It would be more efficient for you to update an existing collection instead. You can do this with the Stream.collect method.

Java-8 12 Stream 12


Explore Tutu'rself