stock market

Stream API in Java 8: Complete Guide with Examples

Spread the love

Stream api is a powerful abstraction for processing sequence of elements in a functional and declarative style . it allows developers to perform complex data manipulations such as filtering , mapping , sorting and reducing with minimal boilerplate code .

Stream represent a pipeline of operations that can be executed either sequentially or in parallel , improving both readability and performance .

Purpose of Stream Api

The main goals of the stream api are .

1.Simplify data processing:

Replace verbose loops with expressive operations

2.Enable Functional programing :

use lambda expressions and method references

3. Improve Performance:

Support parallel execution with parallel stream .

Pipeline in Java Stream

A stream pipeline consists of three parts .

  • Source
  • Intermediate(Non terminal) operation
  • Terminal operation

1. Source : the data source (eg list , set , array).

2.Intermediate(Non terminal) Operation :

these operations transform the stream , they are lazy and return another stream . laziness in stream means intermediate operations are not executed immediately . they are evaluated when a terminal operation is invoked . this allow for optimization , like short circuiting and avoiding unnecessary computations .

  • filter(Predicate<T>)
  • map(Function<T,R>)
  • flatMap(Function<T,stream<R>>)
  • sorted()
  • sorted(Comperator<T>)
  • distinct()
  • peek(Consumer<T>)
  • limit(long n)
  • skip(long n)

Example:

2.Terminal Method :

These method trigger the execution of the stream pipeline and produce a result or a side effect .once a terminal method is called the stream is consumed and can not be reused .

  • collect(Collectors)
  • forEach(Consumer<T>)
  • reduce(Binaryoperator<T>)
  • count()
  • min(Comperator)
  • max(Comperator)
  • anyMatch()
  • allMatch()
  • findFirst()
  • findAny()

Example:

1.Filtering:-

if we want to filter element from the collection based on some Boolean condition, then we should go for filtering . we can configure filter by using filter() method of stream interface .

2.Mapping:

if we want to create a separate new object for every object present in the collection based on the some function then we should go for mapping mechanism can implement mapping by using map() method of stream interface .

Example :

Leave a Reply

Your email address will not be published. Required fields are marked *