Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java 8 - Closures

Java 8 - Closures

Hands on Kata with Solutions for Functional Interfaces, Closures, Streams and Lambdas in Java 8
Kata: https://github.com/c-guntur/javasig-closures
Solutions: https://github.com/c-guntur/javasig-closures-solutions

C2c1c3d25e26fd444b59e47744c932ba?s=128

Chandra Guntur

October 16, 2014
Tweet

Transcript

  1. ‹#› Goldman Sachs Engineering GS.com/Engineering Summer, 2015

  2. ‹#› Closures In Java 8 Chandra V. Guntur

  3. Confidential “These materials (“Materials”) are confidential and for discussion purposes

    only. The Materials are based on information that we consider reliable, but Goldman Sachs does not represent that it is accurate, complete and/or up to date, and it should not be relied on as such. The Materials do not constitute advice nor is Goldman Sachs recommending any action based upon it. Opinions expressed may not be those of Goldman Sachs unless otherwise expressly noted. As a condition to Goldman Sachs presenting the Materials to you, you agree to treat the Materials in a confidential manner and not disclose the contents thereof without the permission of Goldman Sachs. © Copyright 2015 The Goldman Sachs Group, Inc. All rights reserved.” 3
  4. Confidential 1.JDK 8u45 (installed, path setup). 2.IDE setup with JDK8

    (IntelliJ preferred). 3.Some background with Java and its Collection API. Pre-requisites 4
  5. Confidential • Functional interfaces/lambda expressions introduced. • Internal iterations support

    added. • Many other cool new features … Changes in Java 8 5
  6. Confidential • Most programming languages have closures. • Java had

    closures in a way, with inner classes, but the inner classes can only work with final variables outside of their scope. • Older versions of Java had to deal with external versus internal iterations. • Java thus mostly allowed for passing values not behaviors. Background 6
  7. Confidential • A closure is a function or reference to

    a function together with a referencing environment. • A closure is a function that can access interesting non-local variables. (c2.com) • A closure is really nothing but a dynamically- created function, but when it's created, any variable bindings that are active in its lexical scope can be referenced by the closure, and persist as long as the closure does. (c2.com) What is a closure? 7
  8. Confidential • In anonymous classes, the this keyword resolves to

    the anonymous class, while in a lambda expression this resolves to the enclosing class. • While anonymous classes compile into a Enclosing$Inner class, lambdas (anonymous functions) do not. Lambdas are invoked by a special instruction in the JVM (invokeDynamic). A wee bit of difference 8
  9. Confidential Some Snippets Lambda Expression Syntax (parameters) -> expression (parameters)

    -> statement (parameters) -> { statements } Lambda Examples (int x, int y) -> x * y () -> System.out.println("Hello " + s); (String s) -> { int n = s.length(); return n; } References Static Method Reference /Class::staticMethod Arrays.sort(customers, CustUtil::compare); //Equivalent Lambda Arrays.sort(customers, (a, b) -> CustUtil.compare(a, b)); Instance Method Reference //Class::instanceMethod customers.forEach(System.out::println) //Equivalent Lambda customers.forEach((c) -> System.out.println(c)); Reference to a method of the instance //Class::instanceMethod customers.forEach(Customer::shortInfo); // equivalent to: customers.forEach((c) -> { c.shortInfo(); }); Constructor Reference //Class::constructor Supplier<Customer> customerSupplier = Customer::new; Customer customer = customerSupplier.get(); 9
  10. Confidential Demo time - Chapter 1 10

  11. Confidential • It is all about aggregating data. • Facilitates

    a separation of the how from the what of the problem. Streams focus on the what. • Streams code appears to match the problem statement. • Streams avoid the mashed imperative approach and take on a well-factored style which enhances readability. • Streams allow for a flow of logic via a well-defined pipeline. Streams 11
  12. Confidential Stream pipelines may consist of many operations classified into

    three kinds: 1. Source for the stream. 2. Optional intermediate operations (filter, collect, map etc.). 3. A terminal operation that produces the result (sum, forEach, noneMatch). NOTE: The intermediate operations just setup the recipe for the pipeline (they are lazy), they don’t do anything until a terminal operation is invoked. Streams - continued 12
  13. Confidential Demo time - Chapter 2 13

  14. Confidential 1. Key usage of streams is to filter, map,

    reduce. • Filter: bucket and extract a smaller number of values. • Map: transform/morph data, potentially preserving the number of values. • Reduce: extract a summary value from multiple values. 2. Choose proper operations, for instance, avoid forEach/reduce if you plan on future parallelism; use a collect instead both for thread-safety and statelessness. 3. Be judicious when opting for parallel operations. Checkout Sumatra on OpenJDK if interested in future GPU utilization for parallels. Parallel operations can result in non- deterministic outputs e.g. findAny. 4. Measure, measure and measure - performance is not guaranteed. Use proper tools to measure performance. Checkout jmh (Java Microbenchmarking Harness) on OpenJDK. Points to ponder 14
  15. Confidential • Video: Brian Goetz - Lambdas: A Peek Under

    The Hood (http://parleys.com) • Video: Paul Sandoz - In full flow: Java 8 lambdas in the stream. (http://parleys.com) • Video: Brian Goetz, Paul Sandoz - Java 8 Streams: Lambda in Top Gear. (http://parleys.com) • Tutorial: Java SE 8: Lambda Quick Start (http:// www.oracle.com/webfolder/technetwork/tutorials/obe/ java/Lambda-QuickStart/index.html) Reference material 15
  16. Confidential Some Snippets - Recap Lambda Expression Syntax (parameters) ->

    expression (parameters) -> statement (parameters) -> { statements } Lambda Examples (int x, int y) -> x * y () -> System.out.println("Hello " + s); (String s) -> { int n = s.length(); return n; } References Static Method Reference /Class::staticMethod Arrays.sort(customers, CustUtil::compare); //Equivalent Lambda Arrays.sort(customers, (a, b) -> CustUtil.compare(a, b)); Instance Method Reference //Class::instanceMethod customers.forEach(System.out::println) //Equivalent Lambda customers.forEach((c) -> System.out.println(c)); Reference to a method of the instance //Class::instanceMethod customers.forEach(Customer::shortInfo); // equivalent to: customers.forEach((c) -> { c.shortInfo(); }); Constructor Reference //Class::constructor Supplier<Customer> customerSupplier = Customer::new; Customer customer = customerSupplier.get(); 16
  17. Confidential 1. Attempts to re-use a stream. 2. Accidentally creating

    “infinite” streams. 3. Incorrect order of operations in a stream. 4. Modifying the backing collection while stream being operated. 5. Forgetting to consume the stream (lack of a terminal operation). Common issues and errors 17
  18. Confidential Questions? 18

  19. Learn more at GS.com/Engineering