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

Chandra Guntur

October 16, 2014
Tweet

More Decks by Chandra Guntur

Other Decks in Technology

Transcript

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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