Java 8 Stream API (Valdas Zigas)

download Java 8 Stream API (Valdas Zigas)

of 27

  • date post

    10-May-2015
  • Category

    Technology

  • view

    610
  • download

    0

Embed Size (px)

description

Introduction to Java 8 Stream API with examples.

Transcript of Java 8 Stream API (Valdas Zigas)

  • 1.Stream API Valdas igas kaunas.jug@gmail.com www.kaunas-jug.lt { } Java 8

2. Valdas igas 13.6 x JAVA KTU Program ininerija SCJP 1.5, PL/SQL OCA Oracle University Delivery Instructor LKSoft, BPI, Infor, Affecto. PSE, uTrack 3. Presentation Source Code https://github.com/valdasz/kaunasjug3streamapi.git 4. Java 8 { }. Impression List idList = new ArrayList(); ... idList.stream().distinct().map(EmployeeStreamMain:: findById).filter(e -> e != null).filter(e -> e.getSalary() > 40000).findFirst().orElse(null); 5. Java 8 { }. Impression 12 Years Without Lambdas ... 6. java.util.stream.Stream A sequence of elements supporting sequential and parallel bulk operations public interface Stream extends BaseStream> public interface BaseStream> extends AutoCloseable 7. java.util.stream.BaseStream 8. Simple example. forEach List pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().forEach(p -> System.out.println(p)); StreamFromListSimpleForEach.java 9. Simple example. forEach. Old school List pronouns = Arrays.asList("i", "you", "he", "she", "it", "we", "you", "they"); pronouns.stream().forEach(new Consumer() { public void accept(String p) { System.out.println(p); } }); StreamFromListSimpleForEachOldStyle.java 10. Simple example. filter List 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. Simple example. filter. Old school pronouns.stream().distinct().filter(new Predicate() { public boolean test(String p) { return p.length() == 3; } }).forEach(new Consumer() { public void accept(String p) { System.out.println(p); }}); StreamFromListSimpleFilterOldStyle.java 12. Collection.stream(), Collection.parallelStream() Arrays.stream(T[]) Stream.of(T...) IntStream.range(int, int) Stream.iterate(T, UnaryOperator) Creating streams 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. 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. 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. Creating streams. Infinite. Iterate static Stream iterate(T seed, UnaryOperator f) IntStream.iterate(1, p -> p + 2).limit(10).forEach(System.out:: println); StreamFromStreamInfiniteIterate.java 17. Creating streams. Infinite. Generate static Stream generate(Supplier s) IntStream.generate(() -> (int) (System.nanoTime() % 100)). limit(10) .forEach(System.out::println); StreamFromStreamInfiniteGenerate.java 18. Creating streams BufferedReader.lines Random.ints() File.list Pattern.splitAsStream JarFile.stream() .. StreamFromBufferedReader.java StreamFromPatternSplitAsStream.java 19. Stream features No Storage Functional in nature Laziness-seeking Possibly unbounded Consumable StreamFunctional.java StreamLaziness.java StreamConsumable.java 20. Stream Operators Intermediate (filter, map, limit, sorted ..) Terminal (forEach, reduce, findFirst, sum, collect..) Short-circuiting (intermediate/terminal: limit .. /findFirst..) 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. 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. Parallel Streams Collection.parallelStream() BaseStream.parallel() same results as stream() apart nondeterministic ops (findAny) ParallelStreamFromListSimpleForEach.java ParallelStreamLaziness.java 24. Parallel Streams. Non-interference seq: terminal op starts -> do not update source -> terminal op ends. List l = new ArrayList(Arrays.asList("kaunas-jug", "meeting")); Stream sl = l.parallelStream(); l.add("#3"); String s = sl.collect(Collectors.joining(" ")); System.out.println(s); NonInterference.java 25. Parallel Streams. Stateless behaviours Best approach: avoid stateful behaviour Set seen = Collections.synchronizedSet(new HashSet()); List numbers = Arrays.asList(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3); List result = numbers.parallelStream().map(e -> {return seen.add(e) ? 0 : e; }).collect(Collectors.toList()); StatefulBehaviour.java 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. System.exit(0) Thank You !