Loading...

Stream

A Stream is a sequence of data that you can process in a declaration and functional style.

A Streams are not data structures but tools for performing operations like map-reduce transformation on collections.

A Streams is an Interface that extends AutoCloseable and BaseStream Interfaces.

Advantages of Streams :

1. Not a data structure.

2. Design for Lambda Expression.

3. Donot support indexes access.

5. Lazy access support.

6. Parallelizable.

7. Can easily be outputted as Arrays (or) List.

When to use Streams :

1. Streams is a way to express and process collections of objects.

2. Enable us to perform operations like filtering, mapping, reducing and sorting.

3. Use terminal operations when you're ready to initiate the processing and produce a result.

4. Use intermediate operations to set up a pipeline of operations you want to perform on the data.

Types of Operations in Streams :

1. Intermediate Operations.

2. Terminal Operations.

3. Short Circuit Operations.

Intermediate Operations :

Intermediate Operations transform the elements of stream and return a new stream as a result.

Intermediate Operations do not produce a final result directly they are usually combined using method chaining.

List of Methods in Intermediate Operations

Methods Return Type Type of Operations Declarations
filter() Stream Intermediate Returns a stream of elements which satisfy the given predicate
map() Stream Intermediate Returns a stream consisting of results after applying given function to elements of the stream.
distinct() Stream Intermediate Returns a stream of unique elements.
sorted() Stream Intermediate Returns a stream consisting of elements sorted according to natural order.
limit() Stream Intermediate Returns a stream consisting first n elements.
skip() Stream Intermediate Returns a stream after skipping first n elements.

Terminal Operations :

Terminal Operations produce a result such as a value (or) a collections.

List of Methods in Terminal Operations

Methods Return Type Type of Operations Declarations
forEach() void Terminal Performs an action on all elements of a stream.
toArray() Object [] Terminal Returns an array containing elements of a stream.
reduce() Type T Terminal Performs reduction operations on elements of a stream using initial value and binary operations.
collect() container of Type R Terminal Return mutable result container such as List or Set.
min() Optional Terminal Return minimum elements in a stream wrapped in an Optional Object.
max() Optional Terminal Return maximum elements in a stream wrapped in an Optional Object.
count() long Terminal Retuns the number of elements in a stream.

Short Circuit Operations :

Short-circuit operations are a subset of terminal operations that do not need to process the entire Stream to produce a result. They can provide an early exit from the stream processing pipeline

List of Methods in Short Circuit Operations

Methods Return Type Type of Operations Declarations
anyMatch() boolean Terminal Returns true if any one elements of a stream matches with given predicate.
allMatch() boolean Terminal Returns true if all elements of a stream matches with given predicate.
noneMatch() boolean Terminal Returns true only if all the elements of a streams doesn't match with given predicate.
findFirst() Optional Terminal Returns first elements of a stream wrapped in an Optional Object.
findAny() Optional Terminal Randomly returns any one element in a stream.

Intermediate Operations Vs Terminal Operations

Intermediate Operations Terminal Operations
Intermediate Operations return stream. Terminal Operations return non-stream values.
Intermediate Operations can be chained together to form a pipeline of operations. Terminal Operations can’t be chained together.
Pipeline of operations may contain any number of intermediate operations. Pipeline of operations can have maximum one terminal operation, that too at the end.
Intermediate operations are lazily loaded. Terminal operations are eagerly loaded.
Intermediate Operations don’t produce end result. Intermediate Operations produce end result.

Sequential Stream Vs Parallel Operations

Sequential Stream Parallel Operations
Runs on a single core of the computer Utilize the multiple cores of the computer
The performance is poor The performance is high
Order is maintained Does not care about the order
Only a single iteration at a time Operates multiple iterations at a time
More reliable and less error Less reliable and error prone
Platform Independent Platform Dependent

Nested Class in Stream API Package (java.util.stream)

Modifier and Type Interface and Description
static interface Stream.Builder<T>
A mutable builder for a Stream.

Methods in Stream API Package (java.util.stream)

Modifier and Type Method and Description
boolean allMatch(Predicate<? super T> predicate)
Returns whether all elements of this stream match the provided predicate.
boolean anyMatch(Predicate<? super T> predicate)
Returns whether any elements of this stream match the provided predicate.
static <T> Stream.Builder<T> builder()
Returns a builder for a Stream.
< R, A > R collect(Collector<? super T,A,R> collector)
Performs a mutable reduction operation on the elements of this stream using a Collector.
< R > R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
Performs a mutable reduction operation on the elements of this stream.
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
long count()
Returns the count of elements in this stream.
Stream<T> distinct()
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
static<T> Stream<T> empty()
Returns an empty sequential Stream.
Stream<T> filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.
Optional<T> findFirst()
Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.
<R> Stream <R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream<? extends R>> mapper)
Returns an DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
IntStream flatMapToInt(Function<? super T,? extends IntStream<? extends R>> mapper)
Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
LongStream flatMapToLong(Function<? super T,? extends LongStream<? extends R>> mapper)
Returns an LongStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
void forEach(Consumer<? super T> action)
Performs an action for each element of this stream.
void forEachOrdered(Consumer<? super T> action)
Performs an action for each element of this stream.
static <T> Stream generate(Supplier<T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.
Stream<T> limit(long maxSize)
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
<R> Stream <R> map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
IntStream mapToInt(ToIntFunction<? super T> mapper)
Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
LongStream mapToLong(ToLongFunction<? super T> mapper)
Returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Optional<T> max(Comparator<? super T> comparator)
Returns the maximum element of this stream according to the provided Comparator.
Optional<T> min(Comparator<? super T> comparator)
Returns the minimum element of this stream according to the provided Comparator.
boolean noneMatch(Predicate<? super T> predicate)
Returns whether no elements of this stream match the provided predicate.
static <T> Stream<T> of(T... values)
Returns a sequential ordered stream whose elements are the specified values.
static <T> Stream<T> of(T t)
Returns a sequential Stream containing a single element.
Stream<T> peek(Consumer<? super T> action)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
Optional<T> reduce(BinaryOperator<T> accumulator)
Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
T reduce(T identity, BinaryOperator<T> accumulator)
Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.
Stream<T> skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
Stream<T> sorted()
Returns a stream consisting of the elements of this stream, sorted according to natural order.
Stream<T> sorted(Comparator<? super T> comparator)
Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
Object[] toArray()
Returns an array containing the elements of this stream.
<A> A[] toArray(IntFunction generator)
Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.