Traverse collection using stream API in Java

Stream API is the powerful API provided in Java 8 from Oracle. This is my best API I ever seen in java because it reduce the coding effort and provides functional programming approach to connect different functions in a pipeline. There are a lot of methods in Stream API which can be used to enhance your programming speed and performance. But I will give you a short touch to stream API which will be related to collection traversing. Each collection have stream() method in it to get the stream from it, because we need to get collection as a stream to traverse on it. Let me show you, what is the difference before and after stream API by showing a short example of traverse collection using stream api and without stream api.

Traverse Collection Using Stream API

Before java 8, we were using loops to traverse the collection. May be after java 8 some programmer still use the same way. ( I was one of them ) Any how let me describe the approaches which are being used to traverse the collection.

Using Enhanced Loop:

Using Iterator Method:

The above methods were frequently used to traverse from the collection before Java 8. Now Java 8 provides Stream API which will decrease the coding effort and will increase the readability. Let me show you how you can traverse collection using stream API. ( To understand it, Lambda knowledge required, we can use Stream API without lambda, but to get the actual benefit of stream, use it with lambda )

Using Stream API

As you see the above example contains just one line of coding. If we are familiar with lambdas we can also use the method reference to reduce the more coding. list.stream().forEach(System.out::println);

Oh but wait wait! Am I blundering? Why we called the extra function stream() if we can easily do the above as follow.

Using Inner Enhance Loop

Now what is the need of Stream API? how it is useful to traverse collection? Ok let me enhance the requirements.

Suppose I want to print sum of Even numbers from the collection then?

Sum Of Even Without Stream API

Sum Of Even Using Stream API

So now you can feel the difference and compare the coding effort or readability. It was a short touch to Stream API. you can explore it and can get more benefits by using a lot of methods from it.

Read more about it from Stream Official Doc.