Streams is a new concept or should be specifically mentioned as an ‘Interface’ that’s been introduced in Java 8. Please make sure to not get confused it with Java I/O Streams. The stream is a sequence of objects and the objective of Stream API is to process the collection of objects. 

In this post, we will see how to perform an addition of the values present in the specified ArrayList using mapToInt & sum methods of Stream API.

Let’s jump onto the code directly without wasting any more time and below code, I’ll explain you the key methods that have been used in the code. 

See Java 8 Streams power to perform Add Operation of the integers of ArrayList... Share on X

Here is a sample ArrayList:

 

Below is the code to add the integers present in the above-mentioned ArrayList:

Example

 

Output:

 

Let me explain a little bit about methods that are being used here from Stream API:

1. mapToInt:

     Package:

              java.util.stream.Stream.mapToInt(ToIntFunction<? super Integer> mapper)

     Description:

              Returns an IntStream consisting of the results of applying the given function to the elements of this stream.

     Operation Type:

              intermediate operation

     Parameters:

    mapper a non-interfering, stateless function to apply to each element

     Returns:

    the new stream

2. sum:

     Package:

               java.util.stream.IntStream.sum()

     Description:

               Returns the sum of elements in this stream. This is a special case of a reduction and is equivalent to:

     Operation Type:

                This is a terminal operation.

     Returns:

       the sum of elements in this stream

 

I would be glad if this post helps you. If you like this post, please tweet it.

See Java 8 Streams power to perform Add Operation of the integers of ArrayList... Share on X

 

If you like this post, please check out my other similar posts:

Double the even / odd numbers of a specified ArrayList using Streams

 

Reference:

Streams Javadoc

Streams in Java

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak