Java 8 Stream API: A Comprehensive Guide for Biomedical Informatics


This guide explores Java 8 Stream API and its relevance in Biomedical Informatics. It covers the outline of stream building blocks, default methods, functional interfaces, lambda expressions, and method references. Furthermore, it discusses the characteristics of streams, creating streams, common functional interfaces used, the anatomy of the stream pipeline, optional class, common Stream API methods, and examples of parallel, unbounded and on-the-fly streams. Finally, it concludes by highlighting what streams could do for BMI.
- Uploaded on | 0 Views
-
selinabogan
About Java 8 Stream API: A Comprehensive Guide for Biomedical Informatics
PowerPoint presentation about 'Java 8 Stream API: A Comprehensive Guide for Biomedical Informatics'. This presentation describes the topic on This guide explores Java 8 Stream API and its relevance in Biomedical Informatics. It covers the outline of stream building blocks, default methods, functional interfaces, lambda expressions, and method references. Furthermore, it discusses the characteristics of streams, creating streams, common functional interfaces used, the anatomy of the stream pipeline, optional class, common Stream API methods, and examples of parallel, unbounded and on-the-fly streams. Finally, it concludes by highlighting what streams could do for BMI.. The key topics included in this slideshow are Java 8, Stream API, Biomedical Informatics, Functional Interfaces, Lambda Expressions,. Download this presentation absolutely free.
Presentation Transcript
1. Java 8 Stream API Raj Thavamani Application Developer / Java Group Biomedical Informatics
2. Outline Stream Building Blocks Java 8 Default Methods Functional Interfaces Lambda Expressions Method References
3. Outline Characteristics of Streams Creating Streams Common Functional Interfaces Used Anatomy of the Stream pipeline Optional Class Common Stream API Methods Used Examples Parallel Streams Unbounded (On the Fly) Streams What Could Streams Do For BMI References Questions?
4. Java 8 Target Release Date: 03/18/14 Introduces Default Methods Functional Interfaces Lambda Expressions Stream API and overall improvements to Collections to support Streams
5. Default Methods In Context of Support For Streams Java 8 needed to add functionality to existing Collection interfaces to support Streams (stream(), forEach())
6. Default Methods Problem Pre-Java 8 interfaces couldnt have method bodies. The only way to add functionality to Interfaces was to declare additional methods which would be implemented in classes that implement the interface It is impossible to add methods to an interface without breaking the existing implementation
7. Default Methods Solution Default Methods! Java 8 allows default methods to be added to interfaces with their full implementation Classes which implement the interface dont have to have implementations of the default method Allows the addition of functionality to interfaces while preserving backward compatibility
8. Default Methods Example public interface A { default void foo(){ System.out.println("Calling A.foo()"); } public class Clazz implements A {} Clazz clazz = new Clazz(); clazz.foo(); // Calling A.foo()
9. Functional Interfaces Interfaces with only one abstract method. With only one abstract method, these interfaces can be easily represented with lambda expressions Example @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); }
10. Lambda expressions A more brief and clearly expressive way to implement functional interfaces Format:
11. Method References Event more brief and clearly expressive way to implement functional interfaces Format:
12. Characteristics of Streams Streams are not related to InputStreams, OutputStreams, etc. Streams are NOT data structures but are wrappers around Collection that carry values from a source through a pipeline of operations. Streams are more powerful, faster and more memory efficient than Lists Streams are designed for lambdas Streams can easily be output as arrays or lists Streams employ lazy evaluation Streams are parallelizable Streams can be on-the-fly
13. Creating Streams From individual values Stream.of(val1, val2, ) From array Stream.of(someArray) Arrays.stream(someArray) From List (and other Collections) someList.stream() someOtherCollection.stream()
14. Common Functional Interfaces Used Predicate
15. Common Functional Interfaces Used Function
16. Common Functional Interfaces Used BiFunction
17. Anatomy of the Stream Pipeline A Stream is processed through a pipeline of operations A Stream starts with a source data structure Intermediate methods are performed on the Stream elements. These methods produce Streams and are not processed until the terminal method is called. The Stream is considered consumed when a terminal operation is invoked. No other operation can be performed on the Stream elements afterwards A Stream pipeline contains some short-circuit methods (which could be intermediate or terminal methods) that cause the earlier intermediate methods to be processed only until the short-circuit method can be evaluated .
18. Anatomy of the Stream Pipeline Intermediate Methods map, filter, distinct, sorted, peek, limit, parallel Terminal Methods forEach, toArray, reduce, collect, min, max, count, anyMatch, allMatch, noneMatch, findFirst, findAny, iterator Short-circuit Methods anyMatch, allMatch, noneMatch, findFirst, findAny,limit
19. Optional
20. Common Stream API Methods Used Void forEach(Consumer) Easy way to loop over Stream elements You supply a lambda for forEach and that lambda is called on each element of the Stream Related peek method does the exact same thing, but returns the original Stream
21. Common Stream API Methods Used Void forEach(Consumer) Example Employees.forEach(e -> e.setSalary(e.getSalary() * 11/10)) Give all employees a 10% raise
22. Common Stream API Methods Used Void forEach(Consumer) Vs. For Loops List
23. Common Stream API Methods Used Stream
24. Common Stream API Methods Used Stream
25. Common Stream API Methods Used Optional
26. Common Stream API Methods Used Object[] toArray(Supplier) Reads the Stream of elements into a an array Example Employee[] empArray = employees.toArray(Employee[]::new); Create an array of Employees out of the Stream of Employees
27. Common Stream API Methods Used List
28. Common Stream API Methods Used List
29. Common Stream API Methods Used T reduce(T identity, BinaryOperator) You start with a seed (identity) value, then combine this value with the first Entry in the Stream, combine the second entry of the Stream, etc. Example Nums.stream().reduce(1, (n1,n2) -> n1*n2) Calculate the product of numbers IntStream (Stream on primative int] has build-in sum() Built-in Min, Max methods
30. Common Stream API Methods Used Stream
31. Common Stream API Methods Used Stream
32. Common Stream API Methods Used Stream
33. Common Stream API Methods Used Optional
34. Common Stream API Methods Used Optional
35. Common Stream API Methods Used Stream
36. Common Stream API Methods Used Boolean anyMatch(Predicate), allMatch(Predicate), noneMatch(Predicate) Returns true if Stream passes, false otherwise Lazy Evaluation anyMatch processes elements in the Stream one element at a time until it finds a match according to the Predicate and returns true if it found a match allMatch processes elements in the Stream one element at a time until it fails a match according to the Predicate and returns false if an element failed the Predicate noneMatch processes elements in the Stream one element at a time until it finds a match according to the Predicate and returns false if an element matches the Predicate Example employeeStream.anyMatch(e -> e.getSalary() > 500000) Is there a rich Employee among all Employees?
37. Common Stream API Methods Used long count() Returns the count of elements in the Stream Example employeeStream.filter(somePredicate).c ount() How many Employees match the criteria?
38. Parallel Streams Helper Methods For Timing private static void timingTest(Stream
39. Parallel Streams Helper Method For Simulating Long Operation void doSlowOp() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ie) { // Nothing to do here. } }
40. Parallel Streams Main Code System.out.print("Serial version [11 entries]:"); timingTest(googlers()); int numProcessorsOrCores = Runtime.getRuntime().availableProcessors(); System.out.printf("Parallel version on %s-core machine:", numProcessorsOrCores); timingTest(googlers(). parallel() );
41. Parallel Streams Results Serial version [11 entries]: 11.000 seconds. Parallel version on 4-core machine: 3.000 seconds.
42. (On The Fly) Streams Stream
43. What Could Streams do For BMI? The real excitement with Streams is when you combine Stream operators into one pipeline Parallel Processing on large Patient Sets Taking advantage of groupingBy and partitioningBy to perform analysis Example1: PvpPatientPicker for ICN A massive datatable that needs to have the ability to filter on any column as well as do nested filtering Think of how much code you would need to implement the filtering Using Streams: List
44. References Stream API http://download.java.net/jdk8/docs/api/java/util/stream/S tream.html Java 8 Explained: Applying Lambdas to Java Collections http://zeroturnaround.com/rebellabs/java-8-explained- applying-lambdas-to-java-collections/ Java 8 first steps with Lambdas and Streams https://blog.codecentric.de/en/2013/10/java-8-first-steps- lambdas-streams/ Java 8Tutorial: Lambda Expressions, Streams, and More http://www.coreservlets.com/java-8-tutorial/
45. Questions?