0% found this document useful (0 votes)
6 views19 pages

Stream Operations 4 ForEachOrdered Count Min Max ToArray 1746979675

The document provides an overview of Java 8+ Stream operations, including methods for removing duplicates, debugging, fetching, and skipping elements in streams. It discusses terminal operations, sequential vs parallel streams, and encounter order, along with examples of using methods like forEach, count, min, max, and toArray. Additionally, it mentions future updates and resources for further learning on the topic.

Uploaded by

formymotoe3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views19 pages

Stream Operations 4 ForEachOrdered Count Min Max ToArray 1746979675

The document provides an overview of Java 8+ Stream operations, including methods for removing duplicates, debugging, fetching, and skipping elements in streams. It discusses terminal operations, sequential vs parallel streams, and encounter order, along with examples of using methods like forEach, count, min, max, and toArray. Additionally, it mentions future updates and resources for further learning on the topic.

Uploaded by

formymotoe3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

STREAM OPERATIONS - 4

Java 8+
Quick Recap -
Project Structure:

Model Classes:
1. Employee
2. Department
3. Address

EmpDeptDto: DTO class having some fields.

Repository Layer: Service Layer:

1. EmployeeRepository 1. EmployeeService

2. DepartmentRepository 2. DepartmentService

Database: DatabaseProxy class consists of static data


Project Structure:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Quick Recap -
Removing Duplicates from Streams - distinct()
distinct() method is used to remove duplicates from a stream
distinct() is a Stateful Intermediate Operation that returns a
stream consisting of the distinct elements (according to Object.
equals(Object)) of this stream.
Duplicate data is a common issue and distinct() helps clean it up.

Ex. Get unique numbers from a list

Output:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Quick Recap -
Debugging Streams - peek()

peek() is an intermediate operation - 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.
peek() method exists mainly to support debugging.
peek() method is used to observe elements during processing
without changing them.

Output:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Quick Recap -
Fetch ‘n’ elements from a Stream - limit()
limit(n) method returns a stream consisting of the elements of
this stream, truncated to be no longer than maxSize in length.
This is a short-circuiting stateful intermediate operation.
limit(n) stops processing the stream after retrieving n elements,
even if more elements are present; so it is a short-circuiting
intermediate operation.
limit(n) must count the elements as it processes the stream to
determine when to stop; so it is a stateful intermediate operation

Ex. Get top 3 highest paid employees (EmployeeRepository)

Output:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Quick Recap -
Ignore ‘n’ elements from a Stream - skip()
skip(n) method returns a stream consisting of the remaining
elements of this stream after discarding the first n elements of
the stream.
If this stream contains fewer than n elements then an empty
stream will be returned.
This is a stateful intermediate operation; as it tracks and
discards the first n elements.

Ex. Skip top 3 highest paid employees and get the remaining
employees (EmployeeRepository)

Output:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Quick Recap -
Ignore ‘n’ elements from a Stream - skip()
skip(n) method returns a stream consisting of the remaining
elements of this stream after discarding the first n elements of
the stream.
If this stream contains fewer than n elements then an empty
stream will be returned.
This is a stateful intermediate operation; as it tracks and
discards the first n elements.

Ex. Skip top 3 highest paid employees and get the remaining
employees (EmployeeRepository)

Output:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

What are Terminal Operations?

Terminal operations trigger the processing of the stream and


produce a result (or a side-effect).
Terminal operations such as forEach and count return a non-
stream value and process a stream pipeline to return a result.
A stream is consumed after a terminal operation — it cannot be
reused.

List of Terminal Operations

forEach toArray
forEachOrdered allMatch
collect anyMatch
reduce noneMatch
max findFirst
min findAny
count

Highlighted Terminal operations have been covered in this


document and the associated video.

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Sequential Streams vs Parallel Streams

Sequential Streams
Processes elements one at a time, in encounter order.
Best for small to medium datasets or when order matters.
Use stream() of Collections method, Stream.of, Stream.iterate, etc.
by default create a sequential stream.

Parallel Streams
Processes elements concurrently using multiple threads.
Parallel streams do not guarantee element processing order,
even if the source is ordered.
Can boost performance on large datasets with multi-core CPUs.
If order matters, use methods like forEachOrdered() or choose
sequential streams.
Create parallel stream:
Use parallel() method on sequential stream
Use parallelStream() method on collection

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

What is Encounter Order in Java Streams?

Encounter Order refers to the order in which elements are


encountered during stream processing, based on the source's
definition (like a List or Set).
Sources like Lists, Arrays and LinkedHashSet maintain encounter
order.
In Parallel Streams, encounter order can be lost unless you
explicitly use forEachOrdered() or ordered collectors.

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
forEach() and forEachOrdered()
Both are terminal operations which executes a provided
Consumer on every element in the stream.
Both methods can produce the same result when used in a
sequential stream.
In a parallel stream, only forEachOrdered will preserve the
encounter order.

Sequential Streams

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
forEach() and forEachOrdered()

Parallel Streams

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
count()
Returns number of elements in Stream
This is a special case of a reduction and is equivalent to:
mapToLong(e -> 1L).sum();

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
min(Comparator) | min()
Returns the minimum element of this stream according to the
provided Comparator. This is a special case of a reduction.
Returns empty optional if stream is empty.
Throws NullPointerException if minimum element is null.
Primitive streams like IntStream, LongStream and DoubleStream
have min() method that takes no argument; as numbers are
naturally comparable.

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
Ex. Get minimum number from DoubleStream
(Primitive stream example)

Ouput:

Ex. Get lowest paid employee

Ouput:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
max(Comparator) | max()
Returns the maximum element of this stream according to the
provided Comparator. This is a special case of a reduction.
Returns empty optional if stream is empty.
Throws NullPointerException if maximum element is null.
Primitive streams like IntStream, LongStream and DoubleStream
have max() method that takes no argument; as numbers are
naturally comparable.

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
Ex. Get maximum number from DoubleStream
(Primitive stream example)

Ouput:

Ex. Get highest paid employee

Ouput:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
toArray() | toArray(IntFunction)
Returns an array containing the elements of this stream.

Returns an array containing the elements of this stream, using


the provided generator function to allocate the returned array

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+
Ex. Get array of doubles from the stream of
Doubles – toArray()

Ouput:

Ex. Get array of employee IDs for employees with experience


less than 5 years – toArray(IntFunction)

Ouput:

#CodingWalaShree
STREAM OPERATIONS - 4
Java 8+

Subscribe
CodingWalaShree
Examples in this presentation are covered in my YouTube Video on
Stream API Part 6🚀

Note: As I cover more terminal operations in upcoming videos


on CodingWalaShree, I’ll update this presentation and share it
on LinkedIn — so stay tuned! 🚀
To be continued. . .

Follow me on https://www.linkedin.com/in/shrikrishna-
prabhumirashi-717b2356/ for interesting insights.

#CodingWalaShree

You might also like