Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Stream API
Valdas Žigas · kaunas.jug@gmail.com · www.kaunas-jug.lt
{ λ }
Java 8
Valdas Žigas
● 13.6 x JAVA
● KTU Programų inžinerija
● SCJP 1.5, PL/SQL OCA
● Oracle University Delivery Instructor
● LKSo...
Presentation Source Code
https://github.com/valdasz/kaunasjug3streamapi.git
Java 8 { λ }. Impression
List<Long> idList = new ArrayList<>();
...
idList.stream().distinct().map(EmployeeStreamMain::
fi...
Java 8 { λ }. Impression
12 Years Without Lambdas ...
java.util.stream.Stream<T>
A sequence of elements supporting sequential
and parallel bulk operations
public interface Stre...
java.util.stream.BaseStream<T>
Simple example. forEach
List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they");
pronoun...
Simple example. forEach. Old school
List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you",
"the...
Simple example. filter
List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you",
"they");
pronouns...
Simple example. filter. Old school
pronouns.stream().distinct().filter(new Predicate<String>() {
public boolean test(Strin...
● Collection.stream(),
Collection.parallelStream()
● Arrays.stream(T[])
● Stream.of(T...)
● IntStream.range(int, int)
● St...
Creating streams. Arrays.stream
Arrays.stream(new String[] { "This", "is", "Java8", "Stream" })
.forEach(System.out::print...
Creating streams. Stream.of
Stream.of("This", "is", "Java8", "Stream").forEach(System.out::println);
Stream.of(new Integer...
Creating streams. IntStream
IntStream.of(new int[] { 1, 2, 3 }).forEach(System.out::println);
IntStream.range(1, 3).forEac...
Creating streams. Infinite. Iterate
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
IntStream.iterate(1, p -> p +...
Creating streams. Infinite. Generate
static <T> Stream<T> generate(Supplier<T> s)
IntStream.generate(() -> (int) (System.n...
Creating streams
● BufferedReader.lines
● Random.ints()
● File.list
● Pattern.splitAsStream
● JarFile.stream()
● ………..
Str...
Stream features
● No Storage
● Functional in nature
● Laziness-seeking
● Possibly unbounded
● Consumable
StreamFunctional....
Stream Operators
● Intermediate (filter, map, limit, sorted ..)
● Terminal (forEach, reduce, findFirst, sum,
collect..)
● ...
Stream Operators. Intermediate
map (mapToInt, flatMap, ..), filter, distinct, sorted, peek, limit, substream, parallel,
se...
Stream Operators. Terminal
forEach, forEachOrdered, toArray, reduce, collect,
min, max, count, findFirst...
● Consumes pip...
Parallel Streams
● Collection.parallelStream()
BaseStream.parallel()
● same results as stream() apart
nondeterministic ops...
Parallel Streams. Non-interference
seq: terminal op starts -> do not update
source -> terminal op ends.
List<String> l = n...
Parallel Streams. Stateless behaviours
Best approach: avoid stateful behaviour
Set<Integer> seen = Collections.synchronize...
Parallel Streams. reduce. Associativity
(a op b) op c == a op (b op c)
a op b op c op d == (a op b) op (c op d)
IntStream ...
System.exit(0)
Thank You !
Upcoming SlideShare
Loading in …5
×

Java 8 Stream API (Valdas Zigas)

1,695 views

Published on

Introduction to Java 8 Stream API with examples.

Published in: Technology, Education

Java 8 Stream API (Valdas Zigas)

  1. 1. Stream API Valdas Žigas · kaunas.jug@gmail.com · www.kaunas-jug.lt { λ } Java 8
  2. 2. Valdas Žigas ● 13.6 x JAVA ● KTU Programų inžinerija ● SCJP 1.5, PL/SQL OCA ● Oracle University Delivery Instructor ● LKSoft, BPI, Infor, Affecto. PSE, uTrack
  3. 3. Presentation Source Code https://github.com/valdasz/kaunasjug3streamapi.git
  4. 4. Java 8 { λ }. Impression List<Long> idList = new ArrayList<>(); ... idList.stream().distinct().map(EmployeeStreamMain:: findById).filter(e -> e != null).filter(e -> e.getSalary() > 40000).findFirst().orElse(null);
  5. 5. Java 8 { λ }. Impression 12 Years Without Lambdas ...
  6. 6. java.util.stream.Stream<T> A sequence of elements supporting sequential and parallel bulk operations public interface Stream<T> extends BaseStream<T, Stream<T>> public interface BaseStream<T, S extends BaseStream<T, S>> extends AutoCloseable
  7. 7. java.util.stream.BaseStream<T>
  8. 8. Simple example. forEach List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().forEach(p -> System.out.println(p)); StreamFromListSimpleForEach.java
  9. 9. Simple example. forEach. Old school List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().forEach(new Consumer<String>() { public void accept(String p) { System.out.println(p); } }); StreamFromListSimpleForEachOldStyle.java
  10. 10. Simple example. filter List<String> pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().distinct().filter(p -> p.length() == 3).forEach(p -> System.out.println(p)); StreamFromListSimpleFilter.java
  11. 11. Simple example. filter. Old school pronouns.stream().distinct().filter(new Predicate<String>() { public boolean test(String p) { return p.length() == 3; } }).forEach(new Consumer<String>() { public void accept(String p) { System.out.println(p); }}); StreamFromListSimpleFilterOldStyle.java
  12. 12. ● Collection.stream(), Collection.parallelStream() ● Arrays.stream(T[]) ● Stream.of(T...) ● IntStream.range(int, int) ● Stream.iterate(T, UnaryOperator<T>) Creating streams
  13. 13. Creating streams. Arrays.stream Arrays.stream(new String[] { "This", "is", "Java8", "Stream" }) .forEach(System.out::println); Arrays.stream(new Integer[] { 1, 2, 3 }).forEach(System.out::println); Arrays.stream(new int[] { 1, 2, 3 }).forEach(System.out::println); StreamFromArraysStream.java
  14. 14. Creating streams. Stream.of Stream.of("This", "is", "Java8", "Stream").forEach(System.out::println); Stream.of(new Integer[] { 1, 2, 3 }).forEach(System.out::println); Stream.of(new int[] { 1, 2, 3 }).forEach(System.out::println); StreamFromStreamOf.java
  15. 15. Creating streams. IntStream IntStream.of(new int[] { 1, 2, 3 }).forEach(System.out::println); IntStream.range(1, 3).forEach(System.out::println); IntStream.rangeClosed(1, 3).forEach(System.out::println); IntStreamFromIntStream.java
  16. 16. Creating streams. Infinite. Iterate static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) IntStream.iterate(1, p -> p + 2).limit(10).forEach(System.out:: println); StreamFromStreamInfiniteIterate.java
  17. 17. Creating streams. Infinite. Generate static <T> Stream<T> generate(Supplier<T> s) IntStream.generate(() -> (int) (System.nanoTime() % 100)). limit(10) .forEach(System.out::println); StreamFromStreamInfiniteGenerate.java
  18. 18. Creating streams ● BufferedReader.lines ● Random.ints() ● File.list ● Pattern.splitAsStream ● JarFile.stream() ● ……….. StreamFromBufferedReader.java StreamFromPatternSplitAsStream.java
  19. 19. Stream features ● No Storage ● Functional in nature ● Laziness-seeking ● Possibly unbounded ● Consumable StreamFunctional.java StreamLaziness.java StreamConsumable.java
  20. 20. Stream Operators ● Intermediate (filter, map, limit, sorted ..) ● Terminal (forEach, reduce, findFirst, sum, collect..) ● Short-circuiting (intermediate/terminal: limit .. /findFirst..)
  21. 21. Stream Operators. Intermediate map (mapToInt, flatMap, ..), filter, distinct, sorted, peek, limit, substream, parallel, sequential, unordered .. ● Return new Stream ● Always lazy ● Stateless/stateful filter,map/distinct,sorted ● Some short-circuiting (limit)
  22. 22. Stream Operators. Terminal forEach, forEachOrdered, toArray, reduce, collect, min, max, count, findFirst... ● Consumes pipeline/terminates ● Eager (except iterator, spliterator) ● some short-circuiting (findFirst, findAny)
  23. 23. Parallel Streams ● Collection.parallelStream() BaseStream.parallel() ● same results as stream() apart nondeterministic ops (findAny) ParallelStreamFromListSimpleForEach.java ParallelStreamLaziness.java
  24. 24. Parallel Streams. Non-interference seq: terminal op starts -> do not update source -> terminal op ends. List<String> l = new ArrayList<String>(Arrays.asList("kaunas-jug", "meeting")); Stream<String> sl = l.parallelStream(); l.add("#3"); String s = sl.collect(Collectors.joining(" ")); System.out.println(s); NonInterference.java
  25. 25. Parallel Streams. Stateless behaviours Best approach: avoid stateful behaviour Set<Integer> seen = Collections.synchronizedSet(new HashSet<>()); List<Integer> numbers = Arrays.asList(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3); List<Integer> result = numbers.parallelStream().map(e -> {return seen.add(e) ? 0 : e; }).collect(Collectors.toList()); StatefulBehaviour.java
  26. 26. Parallel Streams. reduce. Associativity (a op b) op c == a op (b op c) a op b op c op d == (a op b) op (c op d) IntStream stream = IntStream.rangeClosed(1, 4). parallel(); OptionalInt rez = stream.reduce((x, y) -> x - y) ReduceAssociativity.java
  27. 27. System.exit(0) Thank You !

×