SlideShare a Scribd company logo
1 of 82
Download to read offline
Java8: Stream Style
Sergey Kuksenko
sergey.kuksenko@oracle.com, @kuksenk0
The following is intended to outline our general product direction. It
is intended for information purposes only, and may not be
incorporated into any contract. It is not a commitment to deliver any
material, code, or functionality, and should not be relied upon in
making purchasing decisions. The development, release, and timing
of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Slide 2/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Slide 3/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Everything is well. Why do we need any Streams?
Slide 4/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Everything is well. Why do we need any Streams?
public void printGroups(List <People > people) {
Set <Group > groups = new HashSet <>();
for (People p : people) {
if (p.getAge () >= 65)
groups.add(p.getGroup ());
}
List <Group > sorted = new ArrayList <>(groups );
Collections.sort(sorted , new Comparator <Group >() {
public int compare(Group a, Group b) {
return Integer.compare(a.getSize(), b.getSize ())
}
});
for (Group g : sorted)
System.out.println(g.getName ());
}
Slide 4/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
It would be awesome to omit miles and miles of duplicated code.
public void printGroups(List <People > people) {
people.stream ()
.filter(p -> p.getAge () > 65)
.map(p -> p.getGroup ())
.distinct ()
.sorted(comparing(g -> g.getSize ()))
.map(g -> g.getName ())
.forEach(n -> System.out.println(n));
}
Slide 5/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
It would be awesome to do less work, and do it later (laziness).
public void printGroups(List <People > people) {
people.stream ()
.filter(p -> p.getAge () > 65)
.map(p -> p.getGroup ())
.distinct ()
.sorted(comparing(g -> g.getSize ()))
.map(g -> g.getName ())
.forEach(n -> System.out.println(n));//⇐ ACTIONS!
}
Slide 6/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Parallelism?
Collection <Item > data;
...
for(int i=0; i < data.size (); i++) {
processItem(data.get(i));
}
Slide 7/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Parallelism?
Collection <Item > data;
...
for(Item item : data) {
processItem(item);
}
Slide 8/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Parallelism?
Collection <Item > data;
...
#pragma omg parallel
for(Item item : data) {
processItem(item);
}
Slide 9/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Parallelism?
Collection <Item > data;
...
#pragma omp parallel
for(Item item : data) {
processItem(item);
}
Slide 10/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Parallelism?
Collection <Item > data;
...
parallel_for(Item item : data) {
processItem(item);
}
Slide 11/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Motivation
Parallelism!
Collection <Item > data;
...
data.parallelStream ()
.forEach(item -> processItem(item ));
Slide 12/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Slide 13/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 →
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → 𝑔𝑎𝑛𝑔𝑛𝑎𝑚𝑠𝑡𝑦𝑙𝑒
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → 𝑠𝑖𝑛𝑘
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Design
Most of the code fits the same simple pattern
𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → 𝑠𝑖𝑛𝑘
“sources”: collections, iterators, channels, ...
“operations”: filter, map, reduce, ...
“sinks”: collections, locals, ...
Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Sources
Standard classes?
not-yet-created classes?
3 𝑟𝑑
party classes?
Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Sources
Standard classes?
not-yet-created classes?
3 𝑟𝑑
party classes?
Collection?
should we put everything into collection?
Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Sources
Standard classes?
not-yet-created classes?
3 𝑟𝑑
party classes?
Collection?
should we put everything into collection?
Iterable?
“Iterator Hell” (inherently sequential)
interface pollution
Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Sources
Standard classes?
not-yet-created classes?
3 𝑟𝑑
party classes?
Collection?
should we put everything into collection?
Iterable?
“Iterator Hell” (inherently sequential)
interface pollution
Stream!
new (just invented) interface with required semantic
inject the only stream() method into existing classes
Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream
Slide 16/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream
“A multiplicity of values”
Not a collection (no storage)
Operations are deferred as long as possible
May be infinite
Source is unmodifiable
Can be used only once
Ordered/Unordered
Parallel/Sequential
Primitive specializations:
IntStream, LongStream, DoubleStream
Slide 17/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream pipeline
𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream
𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream
𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT!
public void printGroups(List <People > people) {
people.stream()
.filter(p -> p.getAge () > 65)
.map(p -> p.getGroup ())
.distinct()
.sorted(comparing(g -> g.getSize ()))
.map(g -> g.getName ())
.forEach(n -> System.out.println(n));
}
Slide 18/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream pipeline
𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream
𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream
𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT!
public void printGroups(List <People > people) {
people.stream()
.filter(p -> p.getAge () > 65)
.map(p -> p.getGroup ())
.distinct()
.sorted(comparing(g -> g.getSize ()))
.map(g -> g.getName ())
.forEach(n -> System.out.println(n));
}
Slide 18/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream pipeline
𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream
𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream
𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT!
public void printGroups(List <People > people) {
people.stream()
.filter(p -> p.getAge () > 65)
.map(p -> p.getGroup ())
.distinct()
.sorted(comparing(g -> g.getSize ()))
.map(g -> g.getName ())
.forEach(n -> System.out.println(n));
}
Slide 18/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream pipeline
𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream
𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream
𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT!
public void printGroups(List <People > people) {
Stream <People > s1 = people.stream ();
Stream <People > s2 = s1.filter(p -> p.getAge () > 65);
Stream <Group > s3 = s2.map(p -> p.getGroup ());
Stream <Group > s4 = s3.distinct ();
Stream <Group > s5 = s4.sorted(comparing(g->g.getSize ()));
Stream <String > s6 = s5.map(g -> g.getName ());
s6.forEach(n -> System.out.println(n));
}
Slide 19/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources
Slide 20/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: collections
ArrayList <T> list;
Stream <T> s = list.stream (); // sized , ordered
Slide 21/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: collections
ArrayList <T> list;
Stream <T> s = list.stream (); // sized , ordered
HashSet <T> set;
Stream <T> s = set.stream (); // sized , distinct
Slide 21/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: collections
ArrayList <T> list;
Stream <T> s = list.stream (); // sized , ordered
HashSet <T> set;
Stream <T> s = set.stream (); // sized , distinct
TreeSet <T> set;
Stream <T> s = set.stream (); // sized , distinct
// sorted , ordered
Slide 21/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: factories, builders
T[] arr;
Stream <T> s = Arrays.stream(arr);
Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: factories, builders
T[] arr;
Stream <T> s = Arrays.stream(arr);
Stream <T> s = Stream.of(v0, v1, v2);
Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: factories, builders
T[] arr;
Stream <T> s = Arrays.stream(arr);
Stream <T> s = Stream.of(v0, v1, v2);
Stream <T> s = Stream.builder ()
.add(v0).add(v1).add(v2)
.build ();
Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: factories, builders
T[] arr;
Stream <T> s = Arrays.stream(arr);
Stream <T> s = Stream.of(v0, v1, v2);
Stream <T> s = Stream.builder ()
.add(v0).add(v1).add(v2)
.build ();
IntStream s = IntStream.range(0, 100);
Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: generators
AtomicInteger init = new AtomicInteger (0);
Stream <Integer > s =
Stream.generate(init:: getAndIncrement );
Slide 23/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: generators
AtomicInteger init = new AtomicInteger (0);
Stream <Integer > s =
Stream.generate(init:: getAndIncrement );
Stream <Integer > s = Stream.iterate(0, i -> i+1);
Slide 23/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: others
Stream <String > s = bufferedReader.lines ();
Slide 24/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: others
Stream <String > s = bufferedReader.lines ();
Stream <String > s = Pattern.compile(myRegEx)
.splitAsStream(myStr);
Slide 24/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream Sources: others
Stream <String > s = bufferedReader.lines ();
Stream <String > s = Pattern.compile(myRegEx)
.splitAsStream(myStr);
DoubleStream s =
new SplittableRandom (). doubles ();
Slide 24/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Intermediate Operations
Slide 25/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Intermediate Operations
Stream <S> s;
Stream <S> s.filter(Predicate <S>);
Stream <T> s.map(Function <S, T>);
Stream <T> s.flatMap(Function <S, Stream <T>>);
Stream <S> s.peek(Consumer <S>);
Stream <S> s.sorted ();
Stream <S> s.distinct ();
Stream <S> s.limit(long);
Stream <S> s.skip(long);
Slide 26/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Intermediate Operations
Stream <S> s;
Stream <S> s.filter(Predicate <S>);
Stream <T> s.map(Function <S, T>);
Stream <T> s.flatMap(Function <S, Stream <T>>);
Stream <S> s.peek(Consumer <S>);
Stream <S> s.sorted ();
Stream <S> s.distinct ();
Stream <S> s.limit(long);
Stream <S> s.skip(long);
Stream <S> s.unordered ();
Stream <S> s.parallel ();
Stream <S> s.sequential ();
Slide 26/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Terminal Operations a.k.a. PROFIT
Slide 27/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Terminal Operations
Terminal operations yield final result
Parallel or sequential execution
Terminal operations ’flavors’:
iteration: forEach, iterator
searching: findFirst, findAny
matching: allMatch, anyMatch, noneMatch
aggregation:
𝑟𝑒𝑑𝑢𝑐𝑡𝑖𝑜𝑛
𝑐𝑜𝑙𝑙𝑒𝑐𝑡𝑜𝑟𝑠
Slide 28/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Short-circuiting
Do not consume the entire stream, drop it on the floor as
necessary
May operate infinite streams
find*, *Match, limit
e.g.:
int v = Stream.iterate(1, i -> i+1)
.filter( i % 2 == 0)
.findFirst (). get();
Slide 29/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Iteration
Process each stream element:
IntStream.range(0, 100)
.forEach(System.out:: println );
Convert to old style iterator
1
:
Iterator <Integer > =
Stream.iterate(0, i -> i + 1)
.limit (100)
.iterator ();
1for compatibility
Slide 30/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
How to compute a sum over Stream<Integer>?
Slide 31/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
How to compute a sum over Stream<Integer>?
public int getSum(Stream <Integer > s){
int sum;
s.forEach( i -> sum += i);
return sum;
}
Slide 31/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
How to compute a sum over Stream<Integer>?
public int getSum(Stream <Integer > s){
int sum;
s.forEach( i -> sum += i); // Compile error
return sum;
}
Slide 32/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
How to compute a sum over Stream<Integer>?
public int getSum(Stream <Integer > s){
int[] sum = new int [1];
s.forEach( i -> sum[0] += i);
return sum [0];
}
Slide 33/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
Result?
Stream <Integer > s = IntStream.range(0, 100)
.mapToObj(i -> 1);
System.out.println(getSum(s));
Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
Result?
Stream <Integer > s = IntStream.range(0, 100)
.mapToObj(i -> 1);
System.out.println(getSum(s));
100
Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
Result?
Stream <Integer > s = IntStream.range(0, 100)
.mapToObj(i -> 1);
System.out.println(getSum(s));
100
Stream <Integer > s = IntStream.range(0, 100)
.mapToObj(i -> 1)
.parallel ();
System.out.println(getSum(s));
Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Example
Result?
Stream <Integer > s = IntStream.range(0, 100)
.mapToObj(i -> 1);
System.out.println(getSum(s));
100
Stream <Integer > s = IntStream.range(0, 100)
.mapToObj(i -> 1)
.parallel ();
System.out.println(getSum(s));
79, 63, 100, ...
Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Reduction
Take a stream and make a scalar value:
Stream <Integer > s;
Integer sum = s.reduce(0, (x, y) -> x + y);
Slide 35/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Reduction
Take a stream and make a scalar value:
Stream <Integer > s;
Integer sum = s.reduce(0, (x, y) -> x + y);
Some operations return Optional<T>:
Stream <Integer > s;
Optional <Integer > sum = s.reduce ((x, y) -> x + y);
Slide 35/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Reduction
Stream <T> {
...
<U> U reduce(U identity ,
BiFunction <U,T,U> accumulator ,
BinaryOperator <U> combiner)
...
}
Slide 36/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
A.k.a. mutable reduction operations
Accumulate elements into a mutable result container:
List <Integer > list = IntStream.range(0, 100)
.boxed ()
.collect(Collectors.toList ());
int[] ints = IntStream.range(0, 100). toArray ();
Slide 37/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
A.k.a. mutable reduction operations
Accumulate elements into a mutable result container:
List <Integer > list = IntStream.range(0, 100)
.boxed ()
.collect(Collectors.toList ());
int[] ints = IntStream.range(0, 100). toArray ();
Complex collections:
Map <Integer ,Integer > map = IntStream.range(0, 100)
.boxed (). collect(
Collectors.toConcurrentMap(
k -> k % 42, v -> v, (a, b) -> b
)
);
Slide 37/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
java.util.stream.Collectors
More than 30 predefined collectors, e.g.:
collector => result of Stream<T>.collect(collector)
toList () => List
toSet() => Set
toCollection(Supplier <Collection <T>>) => Collection <T>
partitioningBy(Predicate <T>) => Map <Boolean , List <T>>
groupingBy(Function <T,K>) => Map <K, List <T>>>
toMap(Function <T,K>,
Function <T,U>) => Map <K,U>
Slide 38/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
String [] a = new String []{"a", "b", "c"};
Hot to get "a,b,c"?
Slide 39/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
String [] a = new String []{"a", "b", "c"};
Hot to get "a,b,c"?
Arrays.stream(a). collect(Collectors.joining(","));
Slide 39/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
String [] a = new String []{"a", "b", "c"};
Hot to get "a,b,c"?
Arrays.stream(a). collect(Collectors.joining(","));
FYI: java.util.StringJoiner
Slide 39/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
Stream <T> {
...
<R> R collect(Supplier <R> supplier ,
BiConsumer <R, T> accumulator ,
BiConsumer <R, R> combiner)
...
}
Slide 40/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
Stream <T> s;
List <T> l = s.collect(Collectors.toList ());
⇓
l = collect( () -> new ArrayList <>(),
(list , t) -> list.add(t),
(l1 , l2) -> l1.addAll(l2));
Slide 41/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Collectors
Stream <T> s;
List <T> l = s.collect(Collectors.toList ());
⇓
l = collect( () -> new ArrayList <>(),
(list , t) -> list.add(t),
(l1 , l2) -> l1.addAll(l2));
⇓
l = collect( ArrayList ::new , List::add , List:: addAll );
Slide 41/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Parallelism
Slide 42/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Parallelism
Lots of sources are naturally splittable
Lots of operations are well parallelizable
Streams will do it for us
“ForkJoinPool inside”
Have to ask for the parallelism explicitly
int v = list.parallelStream ()
.reduce(Math::max)
.get();
Slide 43/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Explicit parallelism
Q: Why not implicit?
A: Final speedup depends on:
𝑁 – number of source elements
𝑄 – cost of operation
𝑃 – available HW parallelism
𝐶 – number of concurrent clients
We know 𝑁.
We can estimate 𝑃.
We can somehow cope with 𝐶
𝑄 is almost not predictable.
Slide 44/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Thank you!
Slide 45/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Q & A ?
Slide 46/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Appendix
Slide 47/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Spliterator
Slide 48/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Spliterator
interface Spliterator <T> {
...
long estimateSize (); // Long.MAX_VALUE if unknown
boolean tryAdvance(Consumer <T> action );
Spliterator <T> trySplit ();
int characteristics ();
...
}
Slide 49/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Spliterator’s characteristic
ORDERED
DISTINCT
SORTED
SIZED
SUBSIZED
NONNULL
IMMUTABLE
CONCURRENT
Slide 50/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
Stream design
I like to look at this as having chosen a design center that recognizes
that sequential is a degenerate case of parallel, rather than treating
parallel as the “weird bonus mode”. I realize that this choice was
controversial and definitely caused some compromises, but eventually
people will have to start to unlearn their sequential biases, and
there’s no time like the present.
(c) Brian Goetz
http://mail.openjdk.java.net/pipermail/lambda-dev/2014-February/011870.html
Slide 51/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.

More Related Content

What's hot

Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemGuardSquare
 
Next Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingNext Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingTao Xie
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itAlexey Fyodorov
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeVíctor Leonel Orozco López
 
Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streams
Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streamsTech talks annual 2015 kirk pepperdine_ripping apart java 8 streams
Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streamsTechTalks
 
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos ToolkitExploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos ToolkitSylvain Hellegouarch
 
Kernel Recipes 2013 - Automating source code evolutions using Coccinelle
Kernel Recipes 2013 - Automating source code evolutions using CoccinelleKernel Recipes 2013 - Automating source code evolutions using Coccinelle
Kernel Recipes 2013 - Automating source code evolutions using CoccinelleAnne Nicolas
 
Real-time Computer Vision With Ruby - OSCON 2008
Real-time Computer Vision With Ruby - OSCON 2008Real-time Computer Vision With Ruby - OSCON 2008
Real-time Computer Vision With Ruby - OSCON 2008Jan Wedekind
 
20181106 arie van_deursen_testday2018
20181106 arie van_deursen_testday201820181106 arie van_deursen_testday2018
20181106 arie van_deursen_testday2018STAMP Project
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemGuardSquare
 
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKEric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKGuardSquare
 
ProGuard / DexGuard Tips and Tricks
ProGuard / DexGuard Tips and TricksProGuard / DexGuard Tips and Tricks
ProGuard / DexGuard Tips and Tricksnetomi
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...
Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...
Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...Codemotion
 
Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014Raimon Ràfols
 
Non-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmNon-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmAlexey Fyodorov
 
A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...Valerio Morfino
 

What's hot (20)

Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
Next Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingNext Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized Testing
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
 
First fare 2010 java-beta-2011
First fare 2010 java-beta-2011First fare 2010 java-beta-2011
First fare 2010 java-beta-2011
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
 
Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streams
Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streamsTech talks annual 2015 kirk pepperdine_ripping apart java 8 streams
Tech talks annual 2015 kirk pepperdine_ripping apart java 8 streams
 
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos ToolkitExploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
Exploring OpenFaaS autoscalability on Kubernetes with the Chaos Toolkit
 
Kernel Recipes 2013 - Automating source code evolutions using Coccinelle
Kernel Recipes 2013 - Automating source code evolutions using CoccinelleKernel Recipes 2013 - Automating source code evolutions using Coccinelle
Kernel Recipes 2013 - Automating source code evolutions using Coccinelle
 
Real-time Computer Vision With Ruby - OSCON 2008
Real-time Computer Vision With Ruby - OSCON 2008Real-time Computer Vision With Ruby - OSCON 2008
Real-time Computer Vision With Ruby - OSCON 2008
 
20181106 arie van_deursen_testday2018
20181106 arie van_deursen_testday201820181106 arie van_deursen_testday2018
20181106 arie van_deursen_testday2018
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
Completable future
Completable futureCompletable future
Completable future
 
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKEric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
 
ProGuard / DexGuard Tips and Tricks
ProGuard / DexGuard Tips and TricksProGuard / DexGuard Tips and Tricks
ProGuard / DexGuard Tips and Tricks
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
7.Dead Locks
7.Dead Locks7.Dead Locks
7.Dead Locks
 
Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...
Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...
Fabio Collini - Async code on Kotlin: RxJava or/and coroutines - Codemotion M...
 
Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014
 
Non-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmNon-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithm
 
A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...A comparison of apache spark supervised machine learning algorithms for dna s...
A comparison of apache spark supervised machine learning algorithms for dna s...
 

Similar to Java8 Stream Style

What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8javafxpert
 
CompletableFuture уже здесь
CompletableFuture уже здесьCompletableFuture уже здесь
CompletableFuture уже здесьDmitry Chuyko
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & StreamsC4Media
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much moreAlin Pandichi
 
APEX Connect 2019 - SQL Tuning 101
APEX Connect 2019 - SQL Tuning 101APEX Connect 2019 - SQL Tuning 101
APEX Connect 2019 - SQL Tuning 101Connor McDonald
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Thomas Wuerthinger
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJavaDayUA
 
Robert Meyer- pypet
Robert Meyer- pypetRobert Meyer- pypet
Robert Meyer- pypetPyData
 
PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for GraphsJean Ihm
 
Berlin buzzwords 2018 TensorFlow on Hops
Berlin buzzwords 2018 TensorFlow on HopsBerlin buzzwords 2018 TensorFlow on Hops
Berlin buzzwords 2018 TensorFlow on HopsJim Dowling
 
APEX Connect 2019 - successful application development
APEX Connect 2019 - successful application developmentAPEX Connect 2019 - successful application development
APEX Connect 2019 - successful application developmentConnor McDonald
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On LabSimon Ritter
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
MySQL Optimizer: What's New in 8.0
MySQL Optimizer: What's New in 8.0MySQL Optimizer: What's New in 8.0
MySQL Optimizer: What's New in 8.0Manyi Lu
 
2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation
2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation
2013-07-21 MITRE Developer Days - Red Hat SCAP RemediationShawn Wells
 
Towards a rebirth of data science (by Data Fellas)
Towards a rebirth of data science (by Data Fellas)Towards a rebirth of data science (by Data Fellas)
Towards a rebirth of data science (by Data Fellas)Andy Petrella
 
data mining with weka application
data mining with weka applicationdata mining with weka application
data mining with weka applicationRezapourabbas
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterJAXLondon2014
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Simon Ritter
 

Similar to Java8 Stream Style (20)

What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
CompletableFuture уже здесь
CompletableFuture уже здесьCompletableFuture уже здесь
CompletableFuture уже здесь
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
APEX Connect 2019 - SQL Tuning 101
APEX Connect 2019 - SQL Tuning 101APEX Connect 2019 - SQL Tuning 101
APEX Connect 2019 - SQL Tuning 101
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java Platform
 
Robert Meyer- pypet
Robert Meyer- pypetRobert Meyer- pypet
Robert Meyer- pypet
 
PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for Graphs
 
Berlin buzzwords 2018 TensorFlow on Hops
Berlin buzzwords 2018 TensorFlow on HopsBerlin buzzwords 2018 TensorFlow on Hops
Berlin buzzwords 2018 TensorFlow on Hops
 
APEX Connect 2019 - successful application development
APEX Connect 2019 - successful application developmentAPEX Connect 2019 - successful application development
APEX Connect 2019 - successful application development
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
MySQL Optimizer: What's New in 8.0
MySQL Optimizer: What's New in 8.0MySQL Optimizer: What's New in 8.0
MySQL Optimizer: What's New in 8.0
 
2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation
2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation
2013-07-21 MITRE Developer Days - Red Hat SCAP Remediation
 
Towards a rebirth of data science (by Data Fellas)
Towards a rebirth of data science (by Data Fellas)Towards a rebirth of data science (by Data Fellas)
Towards a rebirth of data science (by Data Fellas)
 
data mining with weka application
data mining with weka applicationdata mining with weka application
data mining with weka application
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
 

Recently uploaded

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Java8 Stream Style

  • 1. Java8: Stream Style Sergey Kuksenko sergey.kuksenko@oracle.com, @kuksenk0
  • 2. The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Slide 2/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 3. Motivation Slide 3/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 4. Motivation Everything is well. Why do we need any Streams? Slide 4/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 5. Motivation Everything is well. Why do we need any Streams? public void printGroups(List <People > people) { Set <Group > groups = new HashSet <>(); for (People p : people) { if (p.getAge () >= 65) groups.add(p.getGroup ()); } List <Group > sorted = new ArrayList <>(groups ); Collections.sort(sorted , new Comparator <Group >() { public int compare(Group a, Group b) { return Integer.compare(a.getSize(), b.getSize ()) } }); for (Group g : sorted) System.out.println(g.getName ()); } Slide 4/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 6. Motivation It would be awesome to omit miles and miles of duplicated code. public void printGroups(List <People > people) { people.stream () .filter(p -> p.getAge () > 65) .map(p -> p.getGroup ()) .distinct () .sorted(comparing(g -> g.getSize ())) .map(g -> g.getName ()) .forEach(n -> System.out.println(n)); } Slide 5/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 7. Motivation It would be awesome to do less work, and do it later (laziness). public void printGroups(List <People > people) { people.stream () .filter(p -> p.getAge () > 65) .map(p -> p.getGroup ()) .distinct () .sorted(comparing(g -> g.getSize ())) .map(g -> g.getName ()) .forEach(n -> System.out.println(n));//⇐ ACTIONS! } Slide 6/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 8. Motivation Parallelism? Collection <Item > data; ... for(int i=0; i < data.size (); i++) { processItem(data.get(i)); } Slide 7/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 9. Motivation Parallelism? Collection <Item > data; ... for(Item item : data) { processItem(item); } Slide 8/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 10. Motivation Parallelism? Collection <Item > data; ... #pragma omg parallel for(Item item : data) { processItem(item); } Slide 9/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 11. Motivation Parallelism? Collection <Item > data; ... #pragma omp parallel for(Item item : data) { processItem(item); } Slide 10/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 12. Motivation Parallelism? Collection <Item > data; ... parallel_for(Item item : data) { processItem(item); } Slide 11/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 13. Motivation Parallelism! Collection <Item > data; ... data.parallelStream () .forEach(item -> processItem(item )); Slide 12/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 14. Design Slide 13/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 15. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 16. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 17. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 18. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 19. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 20. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → 𝑔𝑎𝑛𝑔𝑛𝑎𝑚𝑠𝑡𝑦𝑙𝑒 Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 21. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → 𝑠𝑖𝑛𝑘 Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 22. Design Most of the code fits the same simple pattern 𝑠𝑜𝑢𝑟𝑐𝑒 → 𝑜𝑝 → 𝑜𝑝 → 𝑜𝑝 → 𝑠𝑖𝑛𝑘 “sources”: collections, iterators, channels, ... “operations”: filter, map, reduce, ... “sinks”: collections, locals, ... Slide 14/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 23. Sources Standard classes? not-yet-created classes? 3 𝑟𝑑 party classes? Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 24. Sources Standard classes? not-yet-created classes? 3 𝑟𝑑 party classes? Collection? should we put everything into collection? Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 25. Sources Standard classes? not-yet-created classes? 3 𝑟𝑑 party classes? Collection? should we put everything into collection? Iterable? “Iterator Hell” (inherently sequential) interface pollution Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 26. Sources Standard classes? not-yet-created classes? 3 𝑟𝑑 party classes? Collection? should we put everything into collection? Iterable? “Iterator Hell” (inherently sequential) interface pollution Stream! new (just invented) interface with required semantic inject the only stream() method into existing classes Slide 15/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 27. Stream Slide 16/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 28. Stream “A multiplicity of values” Not a collection (no storage) Operations are deferred as long as possible May be infinite Source is unmodifiable Can be used only once Ordered/Unordered Parallel/Sequential Primitive specializations: IntStream, LongStream, DoubleStream Slide 17/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 29. Stream pipeline 𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream 𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream 𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT! public void printGroups(List <People > people) { people.stream() .filter(p -> p.getAge () > 65) .map(p -> p.getGroup ()) .distinct() .sorted(comparing(g -> g.getSize ())) .map(g -> g.getName ()) .forEach(n -> System.out.println(n)); } Slide 18/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 30. Stream pipeline 𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream 𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream 𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT! public void printGroups(List <People > people) { people.stream() .filter(p -> p.getAge () > 65) .map(p -> p.getGroup ()) .distinct() .sorted(comparing(g -> g.getSize ())) .map(g -> g.getName ()) .forEach(n -> System.out.println(n)); } Slide 18/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 31. Stream pipeline 𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream 𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream 𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT! public void printGroups(List <People > people) { people.stream() .filter(p -> p.getAge () > 65) .map(p -> p.getGroup ()) .distinct() .sorted(comparing(g -> g.getSize ())) .map(g -> g.getName ()) .forEach(n -> System.out.println(n)); } Slide 18/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 32. Stream pipeline 𝑎 𝑠𝑜𝑢𝑟𝑐𝑒: Source → Stream 𝑖𝑛𝑡𝑒𝑟𝑚𝑒𝑑𝑖𝑎𝑡𝑒 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠: Stream → Stream 𝑎 𝑡𝑒𝑟𝑚𝑖𝑛𝑎𝑙 𝑜𝑝𝑒𝑟𝑎𝑡𝑖𝑜𝑛: Stream → PROFIT! public void printGroups(List <People > people) { Stream <People > s1 = people.stream (); Stream <People > s2 = s1.filter(p -> p.getAge () > 65); Stream <Group > s3 = s2.map(p -> p.getGroup ()); Stream <Group > s4 = s3.distinct (); Stream <Group > s5 = s4.sorted(comparing(g->g.getSize ())); Stream <String > s6 = s5.map(g -> g.getName ()); s6.forEach(n -> System.out.println(n)); } Slide 19/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 33. Stream Sources Slide 20/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 34. Stream Sources: collections ArrayList <T> list; Stream <T> s = list.stream (); // sized , ordered Slide 21/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 35. Stream Sources: collections ArrayList <T> list; Stream <T> s = list.stream (); // sized , ordered HashSet <T> set; Stream <T> s = set.stream (); // sized , distinct Slide 21/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 36. Stream Sources: collections ArrayList <T> list; Stream <T> s = list.stream (); // sized , ordered HashSet <T> set; Stream <T> s = set.stream (); // sized , distinct TreeSet <T> set; Stream <T> s = set.stream (); // sized , distinct // sorted , ordered Slide 21/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 37. Stream Sources: factories, builders T[] arr; Stream <T> s = Arrays.stream(arr); Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 38. Stream Sources: factories, builders T[] arr; Stream <T> s = Arrays.stream(arr); Stream <T> s = Stream.of(v0, v1, v2); Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 39. Stream Sources: factories, builders T[] arr; Stream <T> s = Arrays.stream(arr); Stream <T> s = Stream.of(v0, v1, v2); Stream <T> s = Stream.builder () .add(v0).add(v1).add(v2) .build (); Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 40. Stream Sources: factories, builders T[] arr; Stream <T> s = Arrays.stream(arr); Stream <T> s = Stream.of(v0, v1, v2); Stream <T> s = Stream.builder () .add(v0).add(v1).add(v2) .build (); IntStream s = IntStream.range(0, 100); Slide 22/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 41. Stream Sources: generators AtomicInteger init = new AtomicInteger (0); Stream <Integer > s = Stream.generate(init:: getAndIncrement ); Slide 23/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 42. Stream Sources: generators AtomicInteger init = new AtomicInteger (0); Stream <Integer > s = Stream.generate(init:: getAndIncrement ); Stream <Integer > s = Stream.iterate(0, i -> i+1); Slide 23/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 43. Stream Sources: others Stream <String > s = bufferedReader.lines (); Slide 24/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 44. Stream Sources: others Stream <String > s = bufferedReader.lines (); Stream <String > s = Pattern.compile(myRegEx) .splitAsStream(myStr); Slide 24/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 45. Stream Sources: others Stream <String > s = bufferedReader.lines (); Stream <String > s = Pattern.compile(myRegEx) .splitAsStream(myStr); DoubleStream s = new SplittableRandom (). doubles (); Slide 24/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 46. Intermediate Operations Slide 25/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 47. Intermediate Operations Stream <S> s; Stream <S> s.filter(Predicate <S>); Stream <T> s.map(Function <S, T>); Stream <T> s.flatMap(Function <S, Stream <T>>); Stream <S> s.peek(Consumer <S>); Stream <S> s.sorted (); Stream <S> s.distinct (); Stream <S> s.limit(long); Stream <S> s.skip(long); Slide 26/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 48. Intermediate Operations Stream <S> s; Stream <S> s.filter(Predicate <S>); Stream <T> s.map(Function <S, T>); Stream <T> s.flatMap(Function <S, Stream <T>>); Stream <S> s.peek(Consumer <S>); Stream <S> s.sorted (); Stream <S> s.distinct (); Stream <S> s.limit(long); Stream <S> s.skip(long); Stream <S> s.unordered (); Stream <S> s.parallel (); Stream <S> s.sequential (); Slide 26/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 49. Terminal Operations a.k.a. PROFIT Slide 27/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 50. Terminal Operations Terminal operations yield final result Parallel or sequential execution Terminal operations ’flavors’: iteration: forEach, iterator searching: findFirst, findAny matching: allMatch, anyMatch, noneMatch aggregation: 𝑟𝑒𝑑𝑢𝑐𝑡𝑖𝑜𝑛 𝑐𝑜𝑙𝑙𝑒𝑐𝑡𝑜𝑟𝑠 Slide 28/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 51. Short-circuiting Do not consume the entire stream, drop it on the floor as necessary May operate infinite streams find*, *Match, limit e.g.: int v = Stream.iterate(1, i -> i+1) .filter( i % 2 == 0) .findFirst (). get(); Slide 29/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 52. Iteration Process each stream element: IntStream.range(0, 100) .forEach(System.out:: println ); Convert to old style iterator 1 : Iterator <Integer > = Stream.iterate(0, i -> i + 1) .limit (100) .iterator (); 1for compatibility Slide 30/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 53. Example How to compute a sum over Stream<Integer>? Slide 31/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 54. Example How to compute a sum over Stream<Integer>? public int getSum(Stream <Integer > s){ int sum; s.forEach( i -> sum += i); return sum; } Slide 31/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 55. Example How to compute a sum over Stream<Integer>? public int getSum(Stream <Integer > s){ int sum; s.forEach( i -> sum += i); // Compile error return sum; } Slide 32/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 56. Example How to compute a sum over Stream<Integer>? public int getSum(Stream <Integer > s){ int[] sum = new int [1]; s.forEach( i -> sum[0] += i); return sum [0]; } Slide 33/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 57. Example Result? Stream <Integer > s = IntStream.range(0, 100) .mapToObj(i -> 1); System.out.println(getSum(s)); Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 58. Example Result? Stream <Integer > s = IntStream.range(0, 100) .mapToObj(i -> 1); System.out.println(getSum(s)); 100 Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 59. Example Result? Stream <Integer > s = IntStream.range(0, 100) .mapToObj(i -> 1); System.out.println(getSum(s)); 100 Stream <Integer > s = IntStream.range(0, 100) .mapToObj(i -> 1) .parallel (); System.out.println(getSum(s)); Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 60. Example Result? Stream <Integer > s = IntStream.range(0, 100) .mapToObj(i -> 1); System.out.println(getSum(s)); 100 Stream <Integer > s = IntStream.range(0, 100) .mapToObj(i -> 1) .parallel (); System.out.println(getSum(s)); 79, 63, 100, ... Slide 34/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 61. Reduction Take a stream and make a scalar value: Stream <Integer > s; Integer sum = s.reduce(0, (x, y) -> x + y); Slide 35/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 62. Reduction Take a stream and make a scalar value: Stream <Integer > s; Integer sum = s.reduce(0, (x, y) -> x + y); Some operations return Optional<T>: Stream <Integer > s; Optional <Integer > sum = s.reduce ((x, y) -> x + y); Slide 35/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 63. Reduction Stream <T> { ... <U> U reduce(U identity , BiFunction <U,T,U> accumulator , BinaryOperator <U> combiner) ... } Slide 36/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 64. Collectors A.k.a. mutable reduction operations Accumulate elements into a mutable result container: List <Integer > list = IntStream.range(0, 100) .boxed () .collect(Collectors.toList ()); int[] ints = IntStream.range(0, 100). toArray (); Slide 37/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 65. Collectors A.k.a. mutable reduction operations Accumulate elements into a mutable result container: List <Integer > list = IntStream.range(0, 100) .boxed () .collect(Collectors.toList ()); int[] ints = IntStream.range(0, 100). toArray (); Complex collections: Map <Integer ,Integer > map = IntStream.range(0, 100) .boxed (). collect( Collectors.toConcurrentMap( k -> k % 42, v -> v, (a, b) -> b ) ); Slide 37/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 66. java.util.stream.Collectors More than 30 predefined collectors, e.g.: collector => result of Stream<T>.collect(collector) toList () => List toSet() => Set toCollection(Supplier <Collection <T>>) => Collection <T> partitioningBy(Predicate <T>) => Map <Boolean , List <T>> groupingBy(Function <T,K>) => Map <K, List <T>>> toMap(Function <T,K>, Function <T,U>) => Map <K,U> Slide 38/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 67. Collectors String [] a = new String []{"a", "b", "c"}; Hot to get "a,b,c"? Slide 39/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 68. Collectors String [] a = new String []{"a", "b", "c"}; Hot to get "a,b,c"? Arrays.stream(a). collect(Collectors.joining(",")); Slide 39/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 69. Collectors String [] a = new String []{"a", "b", "c"}; Hot to get "a,b,c"? Arrays.stream(a). collect(Collectors.joining(",")); FYI: java.util.StringJoiner Slide 39/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 70. Collectors Stream <T> { ... <R> R collect(Supplier <R> supplier , BiConsumer <R, T> accumulator , BiConsumer <R, R> combiner) ... } Slide 40/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 71. Collectors Stream <T> s; List <T> l = s.collect(Collectors.toList ()); ⇓ l = collect( () -> new ArrayList <>(), (list , t) -> list.add(t), (l1 , l2) -> l1.addAll(l2)); Slide 41/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 72. Collectors Stream <T> s; List <T> l = s.collect(Collectors.toList ()); ⇓ l = collect( () -> new ArrayList <>(), (list , t) -> list.add(t), (l1 , l2) -> l1.addAll(l2)); ⇓ l = collect( ArrayList ::new , List::add , List:: addAll ); Slide 41/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 73. Parallelism Slide 42/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 74. Parallelism Lots of sources are naturally splittable Lots of operations are well parallelizable Streams will do it for us “ForkJoinPool inside” Have to ask for the parallelism explicitly int v = list.parallelStream () .reduce(Math::max) .get(); Slide 43/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 75. Explicit parallelism Q: Why not implicit? A: Final speedup depends on: 𝑁 – number of source elements 𝑄 – cost of operation 𝑃 – available HW parallelism 𝐶 – number of concurrent clients We know 𝑁. We can estimate 𝑃. We can somehow cope with 𝐶 𝑄 is almost not predictable. Slide 44/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 76. Thank you! Slide 45/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 77. Q & A ? Slide 46/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 78. Appendix Slide 47/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 79. Spliterator Slide 48/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 80. Spliterator interface Spliterator <T> { ... long estimateSize (); // Long.MAX_VALUE if unknown boolean tryAdvance(Consumer <T> action ); Spliterator <T> trySplit (); int characteristics (); ... } Slide 49/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 81. Spliterator’s characteristic ORDERED DISTINCT SORTED SIZED SUBSIZED NONNULL IMMUTABLE CONCURRENT Slide 50/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.
  • 82. Stream design I like to look at this as having chosen a design center that recognizes that sequential is a degenerate case of parallel, rather than treating parallel as the “weird bonus mode”. I realize that this choice was controversial and definitely caused some compromises, but eventually people will have to start to unlearn their sequential biases, and there’s no time like the present. (c) Brian Goetz http://mail.openjdk.java.net/pipermail/lambda-dev/2014-February/011870.html Slide 51/51. Copyright c○ 2014, Oracle and/or its affiliates. All rights reserved.