![]() |
VOOZH | about |
The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The method provided by the stream are broadly categorized as
Here, we will be discussing the Intermediate methods of the Stream API. All these methods are in java.util.stream.Stream. Intermediate operators do not execute until a terminal operation is invoked, i.e. they are not executed until a result of processing is actually needed. We will be discussing a few of the important and most frequently used:
Method 1: filter(predicate)
It returns a new stream consisting of the elements of the stream from which it is called which are according to the predicate (condition).
Note:
- Intermediate functions return a stream back.
- On any stream you can execute any number of intermediate operations, but the terminal operation should be single and written at last. So following are the intermediate methods provided by the Stream
- Predicate is a non-interfering, stateless predicate to apply to each element to determine if it should be included or not.
Example
Even numbers are : 20 48 56 32
Method 2: sorted()
Returns a stream consisting of the elements of the stream passed, sorted according to the natural order. If the elements of this stream are not comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
Example
8 19 21 34 45 68 76 99
Method 3: distinct()
It returns a stream consisting of the distinct(different) elements of the passed stream. For ordered stream, the selection of the distinct elements is stable (For duplicated elements, the element appearing first in the encounter order is preserved). While for non-ordered streams it does not make any guarantee for stability.
Example
12 54 63 7 98 72 Sorted List is 7 12 54 63 72 98
Method 4: map()
Mapper is a non-interfering, stateless function to apply to each element of the stream. It returns a stream consisting of the results of applying the given function to the element of the passed stream.
Syntax:
stream().map(mapper)
Implementation:
Example
125 6859 512 12167 216 157464 32768 125 12167 Output after distinct() implementation : 125 6859 512 12167 216 157464 32768 Output after sorted() implementation : 125 216 512 6859 12167 32768 157464 Output after filter() implementation : 125 216 512 6859