You are on page 1of 35

1

JAVA STREAMS
MARCH 2019
AGENDA
 WHAT ARE STREAMS?
 THE STRUCTURE OF STREAMS
2

 TYPES OF STREAMS
 OPERATIONS’ ORDER
 COLLECTIONS VS STREAMS

2
WHAT ARE STREAMS?

A stream in Java is a sequence of elements from a source that supports data


processing operations.

A stream pipeline consists of all the operations


3 that run on a stream to produce a
result.

3
AGENDA
 WHAT ARE STREAMS?
 THE STRUCTURE OF STREAMS
4

 TYPES OF STREAMS
 OPERATIONS’ ORDER
 COLLECTIONS VS STREAMS

4
THE STRUCTURE OF STREAMS

There are three parts to a stream pipeline:

1. Source: where the stream comes from


5
2. Intermediate operations: transforming the stream into another one
3. Terminal operation: produces a result

5
STREAM SOURCES

Stream interface from the java.util.stream package

 Streams from values:


Stream<String> fromValuesString =6 Stream.of(“a”, “b”);
Stream<Integer> fromValuesInteger = Stream.of(1, 2, 3);
FINITE
STREAMS
 Streams from arrays:
List<String> list = Arrays.asList(“a”, “b”);
Stream<String> fromArray = list.stream();

6
STREAM SOURCES

 Streams from functions:


Stream<Double> randoms = Stream.generate(Math::random); INFINITE
STREAMS
Stream<Integer> oddNumbers = Stream.iterate(1,
7 n -> n+2)

7
TERMINAL OPERATIONS
Method Return type Example
allMatch(Predicate<T>)
Stream.iterate(1, n -> n+2)
noneMatch(Predicate<T>) boolean
.allMatch(i -> i%2 == 0);
anyMatch(Predicate<T>)

findFirst() Stream.iterate(1, n -> n+1)


Optional<T>
findAny() .findFirst();
8
forEach(Consumer<T>) void Stream.of(1,2,3).forEach(System.out::print);

max(<? super T>) Stream.of(“Java”, “8”)


Optional<T>
min(<? super T>) .min((s1, s2)-> s1.length() – s2.length());

reduce(...) Optional<T> Stream.of(“w”, “o”, “r”, “d”).reduce(“”, (a,b)-> a+b);

collect(...) R Stream.of(1,2,3).collect(Collectors.toList());
count() long Stream.of(“A”, “B”, “C”).count();

8
TERMINAL OPERATIONS

REDUCE
Terminal operation that is used for
combining a stream into a single result.

int sum = 0; 9
for (int x : numbers) {
sum += x;
}

int sum = numbers.stream()


.reduce(0, (a, b) -> a + b)

9
TERMINAL OPERATIONS

REDUCE
Signatures:
• Optional<T> reduce(BinaryOperator<T> accumulator)
• T reduce(T identity, BinaryOperator<T> accumulator)
• <U> U reduce(U identity, BiFunction<U,? super
10 T,U> accumulator, BinaryOperator<U>
combiner)

Optional<Integer> sum = numbers.stream().reduce((a, b) -> (a + b));

Why does it return an Optional<Integer>? Consider the case when the stream contains
no elements. The reduce operation can’t return a sum because it doesn’t have an initial
value. This is why the result is wrapped in an Optional object to indicate that the sum
may be absent.

10
TERMINAL OPERATIONS

REDUCE

11
Optional<Integer> max = numbers.stream()
.reduce(Integer::max);

11
TERMINAL OPERATIONS

COLLECT

Terminal operation that is used for getting data out of a stream into another form
(e.g. List, Set, Map).
The collect operation accepts a Collector
12 as parameter, which can be a custom
collector, or an already defined collector from the java.util.stream.Collectors class.

<R,A> R collect(Collector<? super T, A,R> collector)

12
TERMINAL OPERATIONS

COLLECT

13

13
TERMINAL OPERATIONS

COLLECT
<R,A> R collect(Collector<? super T, A,R> collector)

Using already defined collectors from the java.util.stream.Collectors class

• List 14

14
TERMINAL OPERATIONS

COLLECT
<R,A> R collect(Collector<? super T, A,R> collector)

Using already defined collectors from the java.util.stream.Collectors class

• Map 15

15
TERMINAL OPERATIONS

COLLECT
<R,A> R collect(Collector<? super T, A,R> collector)

Using already defined collectors from the java.util.stream.Collectors class

• String 16

16
TERMINAL OPERATIONS

COLLECT
<R,A> R collect(Collector<? super T, A,R> collector)

Defining a custom collector using Collector.of()

It takes as parameters: 17
• a supplier: creates and returns a new container that will store the results
• an accumulator: adds a value to the container
• a combiner: merges two accumulators together in case of parallel processing
• a finisher: converts an accumulator to final result type

17
TERMINAL OPERATIONS

COLLECT
<R,A> R collect(Collector<? super T, A,R> collector)

Defining a custom collector using Collector.of()

18

18
TERMINAL OPERATIONS

COLLECT

Defining a custom collector using the collect method with the following
signature:
<R> R collect(Supplier<R> supplier,
BiConsumer<R,19? super T> accumulator,
BiConsumer<R, R> combiner)

19
INTERMEDIATE OPERATIONS

Intermediate operations return another stream as the return type. This allows the
operations to be connected to form a query.
20

Intermediate operations don’t perform any processing until a terminal operation is


invoked on the stream pipeline—they’re lazy. This is because intermediate operations
can usually be merged and processed into a single pass by the terminal operation.

20
INTERMEDIATE OPERATIONS
Method Return type Example
filter(Predicate<T>) Stream<T> persons.stream().filter(i -> i.getName().startsWith(‘A’));
distinct() Stream<T> Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct();
limit(int) Stream<T> Stream.iterate(1, n -> n+2).limit(2);
skip(int) Stream<T> Stream.iterate(1, n -> n+2).skip(2);
21
persons.stream().map(Persons::getName()).sorted();
persons.stream().map(Persons::getName())
sorted()
Stream<T> .sorted(Comparator.naturalOrder());
sorted(Comparator<T>)
persons.stream()
.sorted(Comparator.comparing(Person::getName());
peek(Consumer<T>) Stream<T> persons.stream().peek(System.out::println);
map(Function<T,R>)
persons.stream().map(Persons::getName())
flatMap( Stream<R>
.map(String::length);
Function<T, Stream<R>>)

21
INTERMEDIATE OPERATIONS
MAP VS FLATMAP

Map is used for transforming an object into another object.


Flatmap is used for transforming an object into multiple objects or none at all. The
flatMap() method takes each element in the stream and makes any elements it contains top-
22 lists into a single level and removes empty
level elements in a single stream (flattens nested
lists).

22
AGENDA
 WHAT ARE STREAMS?
 THE STRUCTURE OF STREAMS
23

 TYPES OF STREAMS
 OPERATIONS’ ORDER
 COLLECTIONS VS STREAMS

23
TYPES OF STREAMS
SEQUENTIAL VS PARALLEL STREAMS

 Sequential streams
.stream() on collections
 Parallel streams
.parallelStream() on collections 24

24
TYPES OF STREAMS
SEQUENTIAL VS PARALLEL STREAMS

Turning a sequential stream into a parallel stream

25

Similarly, you can turn a parallel stream into a sequential one by invoking the method
sequential() on it.

25
TYPES OF STREAMS
PRIMITIVE STREAMS

The Stream API comes packed with special streams that work with the
primitive types: int, long, double.
 IntStream
 LongStream
26
 DoubleStream

Differences primitive streams from the regular streams:


• Specialized lambda expressions: IntFunction instead of Function, or IntPredicate
instead of Predicate.
• Two new terminal operations: sum() and average().

26
TYPES OF STREAMS
PRIMITIVE STREAMS

The Stream API comes packed with special streams that work with the
primitive types: int, long, double.

27

27
TYPES OF STREAMS
PRIMITIVE STREAMS

We can transform regular streams to primitive streams using mapping


operations: mapToInt(), mapToLong() and mapToDouble(). To convert back to an
object stream, we use mapToObject().

28

28
AGENDA
 WHAT ARE STREAMS?
 THE STRUCTURE OF STREAMS
29

 TYPES OF STREAMS
 OPERATIONS’ ORDER
 COLLECTIONS VS STREAMS

29
OPERATIONS’ ORDER

One important property of the intermediate operations is their laziness.

30

This means, that if intermediate operations are not followed by a terminal one, they
won’t execute.

30
OPERATIONS’ ORDER

Each element moves along the chain of operations vertically.

31

31
OPERATIONS’ ORDER
OPTIMIZE THE STREAM BY RE-ORDERING THE OPERATIONS

32

32
AGENDA
 WHAT ARE STREAMS?
 THE STRUCTURE OF STREAMS
34

 TYPES OF STREAMS
 OPERATIONS’ ORDER
 COLLECTIONS VS STREAMS

34
COLLECTIONS VS STREAMS

Collections Streams

Eagerly constructed Lazily constructed


Computation of elements beforehand Computation of elements on demand
Modifiable data structure 35 Fixed data structure
Add new elements, remove Cannot add or remove elements from it
Traversable Traversable only once
As many times as needed Only once. Further try results in
IllegalStateException.
External iteration Internal iteration
Requires explicit iteration done by the user Does the iteration behind the scene

35
36

You might also like