What are Streams in Java?
You probably must have heard about stream before Java 8, in a different context while working with input and output ex. FileInputStream and FileOutputStream allowing us to use the contents in the file as stream of bytes or characters.
Java 8 Stream works at a different level on a sequence of elements in a data source like Collections or Arrays. Various intermediate operations can then be pipe-lined together on the Stream to transform or filter the elements and finally the results can be collected in a terminal operation.
Note : Stream maintains the order of the data as it is in the data source.
When was it introduced?
Stream API where introduced as part of Java 8. It provides abstraction on operations that can be performed on sequence of elements.
How to use Streams?
Stream are available to us on Collections, if you check the Java 8 api for Collection interface, you will find that it has default methods like stream and parallelStream, that gives us the Stream object. You would then work with the Stream object using various intermediate operation and terminal operation on them.
Some of the significant intermediate operation available are
- filter
- takes a predicate that can be used to filter our elements that match the condition.
- map
- takes an function as an argument that helps to get mapped elements out of the stream.
- flatMap
- similar to map it takes function as an argument and after mapping flattens the elements of the result into the output stream. Ex: Stream.of(list,list) could be flattened into a single list for consumption.
- distinct
- retrieves distinct values from the stream of elements.
- sorted
- sorts the values in the stream.
Some of the significant terminal operations available are
- reduce
- count
- collect
- forEach
- match
- findFirst
Where to use Streams?
Stream classes support functional-style operations on streams of elements, such as map-reduce transformations on collections. The code written is much cleaner and expressive.
You could achieve performance improvements through the use of parallelStream which help to take advantage of the multi core system.
References: