Unit 4 Concepts of Stream
Unit 4 Concepts of Stream
CONCEPTS OF STREAM
9. CONCEPTS OF STREAM
• Stream was introduced in Java 8, the Stream API is used to process collections of objects.
A stream in Java is a sequence of objects that supports various methods that can be pipelined to
produce the desired result.
Use of Stream in Java
• The uses of Stream in Java are mentioned below:
• Stream API is a way to express and process collections of objects.
• Enable us to perform operations like filtering, mapping, reducing, and sorting.
How to Create a Java Stream?
• Java Stream Creation is one of the most basic steps before considering the functionalities of the
Java Stream. Below is the syntax given for declaring a Java Stream.
Syntax
• Stream<T> stream;
• Here, T is either a class, object, or data type depending upon the declaration.
Java Stream Features
• The features of Java streams are mentioned below:
• A stream is not a data structure; instead, it takes input from the Collections, Arrays, or I/O
channels.
• Streams don’t change the original data structure, they only provide the result as per the pipelined
methods.
• Each intermediate operation is lazily executed and returns a stream as a result, hence, various
intermediate operations can be pipelined. Terminal operations mark the end of the stream and
return the result
Different Operations On Streams
There are two types of Operations in Streams:
1. Intermediate Operations
2. Terminal Operations
Intermediate Operations
Characteristics of Intermediate Operations
• Methods are chained together.
• Intermediate operations transform a stream into another stream.
• It enables the concept of filtering where one method filters data and passes it to another method
after processing.
5. distinct(): Removes duplicate elements. It returns a stream consisting of the distinct elements
(according to Object.equals(Object)).
Syntax:
Stream<T> distinct()
6. peek(): Performs an action on each element without modifying the stream. It 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.
Syntax:
Stream<T> peek(Consumer<? super T> action)
Thank You