DEV Community

Sonali Gupta
Sonali Gupta

Posted on

java 8 (Stream API)

Java 8 introduced stream API which allows developer to process collections of data in functional and declarative way.

Note : unlike collections, a stream does not store the data it only process it.

1.Features of Stream API

1.Declarative : Write concise and readable code using functional style.
2.Lazy Evaluation : Operations are executed only when
needed (terminal operation).
3.Parallel Execution : Supports parallel streams to leverage multi-core processors.
4.Reusable Operations : Supports chaining of operations like map(), filter(), sorted().
5.No Storage : Streams don’t store data; they only process it.

2.How Stream works internally?

1.Create a stream : From collections, arrays or static methods.
2.Apply intermediate operations : Transform data (eg.filter(), map(), sorter() ).
3.Apply Terminal Operation : Produce a result (e.g., forEach(), collect(), reduce()).

3.Creation of streams
Streams creation can be done in multiple ways:

1.From a Collection : Create a stream directly from a List, Set or any Collection using stream()
2.From an Array : Use Arrays.stream(array) to convert an array into a stream.
3.Using Stream.of() : Create a stream from a fixed set of values using Stream.of()
4.Infinite Stream : Generate an unbounded sequence using Stream.iterate() or Stream.generate()

Intermediate operations

Intermediate operations transform a stream into another stream. Some common intermediate operations include:

filter(): Filters elements based on a specified condition.
map(): Transforms each element in a stream to another value.
Sorted(): Sorts the elements of a stream.
Distinct(): Remove duplicates.
Skip(): Skip first n elements.

Types of streams

1.Sequential Stream
Processes elements one by one in a single thread.
Created by default when you call stream().

2.Parallel Streams
Parallel Streams are the type of streams that can perform operations concurrently on multiple threads.

3.infinite Streams
Streams can also generate unbounded sequences. Use limit() to avoid infinite execution.

Top comments (0)