Java 8 Streams

29
An Introduction to Streams Manvendra Singh @Manvendra_SK Java 8

Transcript of Java 8 Streams

An Introduction to Streams

Manvendra Singh

@Manvendra_SK

Java 8

() -> Agenda What is a Stream?

Creating Streams.

Optional Values.

Operations on Streams.

Collecting data using Collectors.

Get code at...git clone

[email protected]:manvendrasinghkadam/java8streams.git

1. What is a Stream?An aggregate operation computes a single value from a collection of values. Result may be primitive value, void or an object which can be a Person, List or Map!

A stream is a sequence of data elements supporting sequential and parallel aggregate operations.

Steams are not collections. Streams focus on aggregate computations on data elements from a data source that is typically, but not necessarily, collections!

... No storage

A collection is an in-memory data structure that stores all its elements. Whereas stream has no storage; it does not store elements.

A stream pulls elements from a data source on-demand and passes them to a pipeline of operations for processing.

... Infinite Streams

A collection cannot represent a group of infinite elements whereas a stream can.

A stream pulls its elements from a data source that can be a collection, a function that generates data, an I/O channel, etc.

Because a function can generate an infinite number of elements, it is possible to have a stream representing a sequence of infinite data elements!

... Imperative vs. Functional

Collections support imperative programming whereas streams support declarative programming.

When we use collections, we need to know what we want and how to get it; this is the feature of imperative programming. When we use streams, we specify only what we want in terms of stream operations; the how part is taken care by the Streams API.

When we use Streams, we specify what operations we want to perform on its elements using the built-in methods provided by the Streams API, typically by passing a lambda expressions to those methods, customizing the behavior of those operations.

Example is here...

... Stream Operations

A Stream support 2 types of operations.

Intermediate operations (Lazy operations).

Terminal operations (Eager operations).

Operations are known as lazy and eager based on the way they pull the data elements from the data source.

A lazy operation on a stream does not process the elements of the stream until another eager operation is called on the stream.

Example is here...

... Stream Operations (cont...)

1, 2,3, 4,

5filter map reduce1, 2, 3, 4, 5 1, 3, 5 1, 9, 25 35

numbers.stream().filter(x -> x % 2 == 1).map(x -> x * x).reduce(0, (x, y) -> x + y);

... Streams are not reusable

Unlike collections, Streams are not reusable. They are one-shot objects.

A Stream cannot be reused after calling a terminal operation on it.

A Stream implementation may throw an IllegalStateException if it detects that the stream is being reused.

Example is here...

... Example explained

2. Creating StreamsThere are many ways to create streams. Many existing classes in the Java libraries have received new methods that return a stream. Based on the data source, stream creation can be categorized as follows:

Streams from values

Empty streams

Streams from Functions

Streams from Arrays

Streams from Collections

Streams from Files

... Streams from values

The Stream interface contains two of() overloaded methods to create a sequential Stream from a single value and multiple values.

Example is here...

... Empty Streams

An empty stream is a stream with no elements.

The Stream interface contains an empty() static method to create an empty sequential stream.

Example is here...

... Streams from Functions

An infinite stream is a stream with a data source capable of generating infinite number of elements.

The Stream interface contains the two static methods to generate an infinite stream:

generate: Generates sequential unordered stream.

iterate: Generates sequential ordered stream.

Example is here...

... Streams from Arrays

The Arrays class in the java.util package contains an overloaded stream() static method to create sequential streams from arrays.

Example is here...

... Streams from Collections

The Collection interface contains the stream() method that create sequential stream.

Example is here...

... Streams from Files

Java 8 has added many methods to the classes in the java.io and java.nio.file packages to support I/O operations using Streams.

Example is here...

3. Optional Valuesnull is used to represent nothing or an empty result. Most often, a method returns null if it does not have a result to return. This has been a source of frequent NullPointerException in Java programs.

Java 8 has introduced an Optional<T> class in the java.util package to deal with NullPointerException gracefully. Methods that may return nothing should return an Optional instead of null.

Actually there is no solution for this NullPointerException. As Optional is the wrapper around null, it throws a NoSuchElementException if the value it contains is null.

Example is here...

4. Operations on Streams

Here is a list of commonly used Stream operations.

distinct – Intermediate

filter – Intermediate

limit – Intermediate

map – Intermediate

peek – Intermediate

skip – Intermediate

sorted – Intermediate

4. Operations on Streams (cont...)

List is continued here...

allMatch – Terminal

anyMatch – Terminal

findAny – Terminal

findFirst – Terminal

noneMatch – Terminal

forEach – Terminal

reduce – Terminal

... Debugging Stream Pipeline

Sometimes we may want to inspect individual elements that we get after certain Stream operation. To do this we Streams API provides us with the peek operation.

Example is here...

... Iteration using Streams

We can iterate the stream using the forEach operation.

Example is here...

... Mapping the Stream elements

A map operation applies a function to each element of the input stream to produce another output stream. The number of elements in the input and output streams is the same. The operation does not modify the elements of the input stream.

Example is here...

... Filtering the Stream elements

The filter operation is applied on an input stream to produce another stream, which is known as the filtered stream. The returned stream by filter operation is a subset of the input stream.

Example is here...

... Reducing the Stream elements

The reduce operation combines all elements of a stream to produce a single value by applying a combining function repeatedly. It is also called reduction operation or a fold.

Computing the sum, maximum, average, count, etc. of elements of a stream of integers are examples of the reduce operation.

Streams API Provides us some specialized methods for reduce operation on Integers, Doubles and Floats..

Example is here...

5. Collecting data using Collectors.

There are several cases in which we want to collect the results of executing a stream pipeline into a collection such as a List, a Set, a Map, etc. Sometimes we may want to apply complex logic to summarize the stream’s data. This is possible using the collect method.

Example is here...

?

For joining in...Thanks