In this article we are going to look into Stream API functionality in java 8. We will also see how to create and use streams in action.
What is Streams?
Java 8 Streams are a wrapper around a data source (Array, List, etc.) allowing us to operate with the data source and making bulk processing of data in fast and convenient way.
Stream does not store data, it is not a data structure and it also not modify the original data source while processing the data. It is a pipeline that process the data from original source and send the processed data to destination data source.
Let’s get into practice
- Stream Creation
Let’s create a stream from an existing Array
we can also obtain stream from existing list
Streams operations are classified into two types
intermediate operations on the initial stream to transform into another stream,there can be more than one intermediate operations.
terminal operation is the final stream to get the result.
Let’s take a look into some of the intermediate operations
~ filter() — filter is an intermediate operation that produces a new stream with the original stream value that pass the given condition(predicate)
Stream<T> filter(Predicate<? super T> predicate)
The above snippet produce the result (‘Java’ ,’JPA’ , ’JMS’). As the filter condition checks for the string starts with ‘J’ so it exclude the string and produces the result.
As we discussed earlier, the stream operation will not change the original data source.
~ map() — map produces the new stream after applying the function to each element of the original stream.
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
Here the map function takes the original stream value and apply the toUpperCase() to all the elements in the source.
~ flatmap() — flatmap is used in case of complex data structure like List<List<String>>, flatmap flatten this data structure to simply further operations.
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
~ distinct() — Returns a stream consisting of the unique elements.
For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made.
~ sorted() — Returns stream consisting of the element of the stream, sorted according to the natural order.
So in this article we had a small hands-on in intermediate stream operations. In the next article we can dive into terminal stream operations with hands-on.
Hope this article is useful!