1. Java SE 8 :Streams
Streams Part 1
1. Overview of Streams
2. Standard Data Structures Into and Out of Streams
3. Core Stream Methods:
3.1 forEach(), map(), filter(), findFirst()
3.2 reduce(), collect(), min(), max(), sorted(), distinct(), limit(), skip(),
noneMatch(), allMatch(), anyMatch(), count()
4. Lazy Evaluation
5. Wrap Up
1Lars Lemos, MCA, OCPJP SE 6
2. Streams Overview
Stream Idea
Streams are wrappers around data sources such as arrays or lists. They provide
many high performance operations that can be expressed with lambdas,
executed sequentially or in parallel.
Example: StreamSamples.java
Note: Streams are not collections. This appear to be an interactive process for n elements over
each method operation. But due to Lazy evaluation there are less iterations performed over each
condition being met.
2
Lars Lemos, MCA, OCPJP SE 6
3. Streams Overview
Stream Idea
Streams are “Not data structures”, they have no storage. They carry values
from a source through a pipeline of operations.
Streams are “Designed for Lambdas”, streams operations take lambdas as
arguments.
Streams don’t have “Indexed access”, you can access the first element, but
not the second or third.
Streams output “Arrays or Lists” easily with simple syntax.
Streams are “Lazy”, the operations are postponed until it is known how much
data is eventually needed.
Example: A operation that takes 10 s/item on a 100 element Stream, selecting the 1st
element takes 10s not 10000s
Streams are “Parallelizable”, once a stream is designated as parallel, then
operations will automatically be done in parallel without having to write
explicit multi-threading code.
Streams can “Ubounded”, once a generator function is designated, clients
can consume entries as long as they want, with values being generated on the
fly.
3
Lars Lemos, MCA, OCPJP SE 6
4. Streams Overview
Creating Stream
It’s known that streams are not collections: they do not manage their own
data (wrappers around data structures).
Thus a stream does not copy the underlying data, only builds a pipeline of
operations. And it can be invoked when desired.
Syntax:
• Individual values - Stream.of(val1, val2, …);
• Array - Stream.of(objectArray);
• Lists - someList.stream();
• StreamBuilder – someBuilder.build();
• String - Stream.of(somestring.split());
4
Lars Lemos, MCA, OCPJP SE 6
6. Streams Overview
Streams to Pre-Java 8 Data Structures
Array
– strm.toArray(EntryType[]::new)
Examples: employeeStream.toArray(Employee[]::new)
– The argument to toArray is normally EntryType[]::new, but in general is a
Supplier that takes an int (size) as an argument and returns an empty array that
can be filled in.
List
– strm.collect(Collectors.toList())
• Common to do “import static java.util.stream.Collectors.*;”
then to do strm.collect(toList())
Other collections
– strm.collect(Collectors.toSet()), – strm.collect(Collectors.groupingBy(…)),
etc.
String
– strm.collect(Collectors.toStringJoiner(delim)).toString()
6
Lars Lemos, MCA, OCPJP SE 6