75
Lambdas and Laughs Jim Bethancourt Houston JUG @jimbethancourt

Lambdas and laughs j1

Embed Size (px)

DESCRIPTION

Lambdas and Laughs talk from JavaOne User Group Sunday

Citation preview

Page 1: Lambdas and laughs   j1

Lambdas and LaughsJim Bethancourt Houston JUG

@jimbethancourt

Page 2: Lambdas and laughs   j1

Forward Looking Statement

Ok, Not Really…

Page 3: Lambdas and laughs   j1

Topics Covered• Lambda Support• Lambda syntax• Interface enhancements• Convert inner class to Lambda• forEach & Streams• Method & Constructor

References• Functional API

Page 4: Lambdas and laughs   j1

Download Links & IDE Support• Regular JDK download link• http://jdk8.java.net/download.html (for EAs)• Netbeans• IntelliJ• Eclipse

Page 5: Lambdas and laughs   j1

Maven Support<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <!-- or higher – up to 3.1 now --> <configuration> <source>1.8</source> <target>1.8</target> </configuration></plugin>

Page 6: Lambdas and laughs   j1
Page 7: Lambdas and laughs   j1
Page 8: Lambdas and laughs   j1

LambdasA lambda expression is like a method: it provides a list of formal parameters and a body—an expression or block—expressed in terms of those parameters.

Expressions:s -> s.length() (int x, int y) -> x+y () -> 42

Assign lambda to functional interface:

Runnable r1 = () -> System.out.println("My Runnable");

Page 9: Lambdas and laughs   j1
Page 10: Lambdas and laughs   j1

LambdasBlocks:(x, y, z) -> {

if (x==y) return x; else { int result = y; for (int i = 1; i < z; i++) result *= i; return result;

}}

Page 11: Lambdas and laughs   j1

Typical Use Cases• Anonymous classes (GUI listeners)• Runnables / Callables• Comparator• Apply operation to a collection via foreach

method• Chain operations on a collection with Stream API

Page 12: Lambdas and laughs   j1
Page 13: Lambdas and laughs   j1
Page 14: Lambdas and laughs   j1

MOAR !!!Monday• Programming with Lambda

Expressions in Java [CON1770]11 AM Hilton Imperial A

• GS Collections and Java 8: Functional, Fluent, Friendly, and Fun [CON5423]11 AM Hilton Imperial B

• Under the Hood of Java 8 Parallel Streams with an Oracle Solaris Dtrace [BOF1937] 9: 45 PM Moscone North 131

Tuesday• Jump-Starting Lambda

[TUT3371]10:30 AM Hilton Yosimite B/C

• Lambda Under the Hood [CON4180]11 AM Hilton Imperial A

• Lambda Q&A Panel [CON3374]1:30 PM Hilton Yosimite B/C

Page 15: Lambdas and laughs   j1

MOAR!!!Thursday• Lambda Programming Laboratory [HOL3373]

2 PM Hilton Franciscan A/B• Lambda-izing JavaFX [CON3248]

3:30 PM Hilton Plaza A

Page 16: Lambdas and laughs   j1
Page 17: Lambdas and laughs   j1

Effectively Final• For both lambda bodies and inner classes, local

variables in the enclosing context can only be referenced if they are final or effectively final.

• A variable is effectively final if its value is not reassigned after its initialization.

• No longer need to litter code with final keyword

Page 18: Lambdas and laughs   j1
Page 19: Lambdas and laughs   j1

Interface Defender Methods• Interface methods with bodies• default keyword• More graceful API evolution• Interfaces have no state• Static methods not inherited• Can reference abstract method• Called “Extended Interfaces” if no abstract methods

present

Page 20: Lambdas and laughs   j1
Page 21: Lambdas and laughs   j1

Super!• Extended Interfaces can

extend other extended interfaces

• Methods can be overridden

• Can decorate parent definitions via super

interface I1 { default void method1() {//do stuff}}interface I2 extends I1{ default void method1() {

super.method1(); //do new stuff }}

Page 22: Lambdas and laughs   j1
Page 23: Lambdas and laughs   j1

Specify the Parent Interfaceinterface D1 { default void meth1() {//do stuff}}interface D2 extends D1{ void default meth1() {super.method1(); //do new stuff}}interface D3 extends D1{ void default meth1() {super.method1(); //do new stuff}}interface D4 extends D2, D3{ void default meth1() {D2.super.method1(); //do new stuff}}

Page 24: Lambdas and laughs   j1
Page 25: Lambdas and laughs   j1

Convert Anonymous Class to Lambdafrom http://learnjavafx.typepad.com/weblog/2013/02/mary-had-a-little-%CE%BB.html

// Anonymous inner class for event handling .onAction(new EventHandler<ActionEvent>() {

@Override public void handle(ActionEvent e) {

anim.playFromStart(); }

})

Page 26: Lambdas and laughs   j1
Page 27: Lambdas and laughs   j1

Convert Anonymous Class to Lambda• .onAction((ActionEvent) -> {

anim.playFromStart(); } }) • .onAction((e) -> {anim.playFromStart();})

Page 28: Lambdas and laughs   j1
Page 29: Lambdas and laughs   j1

Convert Anonymous Class to Lambda• .onAction((ActionEvent) -> {

anim.playFromStart(); } }) • .onAction((e) -> {anim.playFromStart();})• .onAction(e -> { anim.playFromStart(); })• .onAction(e -> anim.playFromStart();)

Page 30: Lambdas and laughs   j1
Page 31: Lambdas and laughs   j1

MOAR!!!• Transforming Code to Java 8 [CON1772]

Thursday 2:30 Hilton Imperial B

Page 32: Lambdas and laughs   j1
Page 33: Lambdas and laughs   j1

forEach• forEach() - available on Iterator & Map interfaces and their

implementations• Allows for internal control of iteration of elements for possible

parallel operationList<String> names =

Arrays.asList(“Bill", “Ed", “Al");names.forEach(e -> { System.out.println(e); });

But be careful!!!

Page 34: Lambdas and laughs   j1
Page 35: Lambdas and laughs   j1
Page 36: Lambdas and laughs   j1
Page 37: Lambdas and laughs   j1

MOAR!!!• GS Collections and Java 8: Functional, Fluent, Friendly,

and Fun [CON5423]Monday 11 AM Hilton Imperial B

• Autumn Collections: From Iterable to Lambdas, Streams, and Collectors [TUT3472]Tuesday 8:30 AM Hilton Yosemite A

• New Tricks for Old Dogs: Collections in Java 8 [CON6309] Thursday 4 PM Hilton Imperial A

Page 38: Lambdas and laughs   j1
Page 39: Lambdas and laughs   j1

java.util.stream• Classes to support functional-style operations

on streams of values• Stream<T> - A sequence of elements

supporting sequential and parallel bulk ops

Page 40: Lambdas and laughs   j1

java.util.stream• Stream opened by calling

– Collection.stream()– Collection.parallelStream()

List<String> names = Arrays.asList("Bill", “Ed", “Al");

out(names.stream().filter(e -> e.length() >= 4 ).findFirst().get());Returns “Bill”

Page 41: Lambdas and laughs   j1

java.util.stream• All other interfaces in stream package

accessible through Stream interface• Collector<T,R> - A (possibly parallel) reduction

operation.• FlatMapper<T,U> - Maps element of type T to

zero or more elements of type U.

Page 42: Lambdas and laughs   j1
Page 43: Lambdas and laughs   j1
Page 44: Lambdas and laughs   j1

MOAR!!!• Journey’s End: Collection and Reduction in the Stream

API [TUT3836]Monday 8:30 AM Hilton Yosemite A

• Programming with Streams in Java 8 [CON1771] Monday 4 PM Hilton Imperial A

• Parallel Streams Workshop [CON3372]Wednesday 10 AM Hilton Yosemite A

• Loads more!!!

Page 45: Lambdas and laughs   j1
Page 46: Lambdas and laughs   j1

java.util• Spliterator<T> provides traversal operations• Optional<T>– Returned by Stream’s aggregate methods

find*(), reduce(), min(), max()

– Call get() to get the value it’s holding

Page 47: Lambdas and laughs   j1
Page 48: Lambdas and laughs   j1

Method & Constructor References• A method reference is used to refer to a (static

or instance) method without invoking it• A constructor reference is similarly used to

refer to a constructor without creating a new instance of the named class or array type.

• Specified with the :: (double colon) operator

Page 49: Lambdas and laughs   j1

Method & Constructor References• Provide a way to refer to a method / constructor without invoking it• Examples:System::getProperty "abc"::length String::length super::toString ArrayList::new int[]::new

Page 50: Lambdas and laughs   j1
Page 51: Lambdas and laughs   j1

Convert call to Method Referencepublic class Test { static void foo(){} static { new Runnable() { @Override public void run() { Test.foo(); } }.run(); }}

Page 52: Lambdas and laughs   j1

Convert call to Method Referencepublic class Test { static void foo(){} static { ((Runnable) () -> Test.foo()).run(); }}

Page 53: Lambdas and laughs   j1

Convert call to Method Referencepublic class Test { static void foo(){} static { ((Runnable) Test::foo()).run(); }}

Page 54: Lambdas and laughs   j1
Page 55: Lambdas and laughs   j1

Use a Method ReferenceThisbttnExit.setOnAction((actionEvent) -> { try { stop(); } catch (Exception e) { // TODO: add error handling} });

Can bebttnExit.setOnAction(

this::onExitButtonClick);...void onExitButtonClick() { try { stop(); } catch (Exception e) { // TODO: add error handling }}

Page 56: Lambdas and laughs   j1

Use a Constructor Referenceinterface Factory<T> { T make(); } Factory<List<String>> f1 = ArrayList::<String>new;• Every time make() is invoked, it will return a

new ArrayList<String>

Page 57: Lambdas and laughs   j1

How many times have you heard

Page 58: Lambdas and laughs   j1
Page 59: Lambdas and laughs   j1

Whatever!Method assigned to privileged interface:public class Main { public static class NotAutoCloseable { public void close() throws Exception { System.out.println("CLOSE"); } }

public static void main(String... args) throws Exception { NotAutoCloseable nac = new NotAutoCloseable(); try (AutoCloseable ac = nac::close) {}}}

Page 60: Lambdas and laughs   j1
Page 61: Lambdas and laughs   j1
Page 62: Lambdas and laughs   j1

Functional Interface• Has just one abstract

method. (Can have other methods with bodies)

• Represents a functional contract.

• The @FunctionalInterface annotation helps ensure the Functional Interface contract is honored

Page 63: Lambdas and laughs   j1

Functional Interface• What happens when you have more than one

abstract method & use @FunctionalInterface?

Page 64: Lambdas and laughs   j1
Page 65: Lambdas and laughs   j1
Page 66: Lambdas and laughs   j1

java.util.function• Functional interfaces provide target types for lambda

expressions and method references• Consumer<T>• Function<T,R>• Supplier<T>• Predicate<T>• Unary/BinaryOperator<T>• Bi(Consumer/Function/Predicate)<T,U(,R)>

Page 67: Lambdas and laughs   j1
Page 68: Lambdas and laughs   j1

public static <X, Y> void processElements(Iterable<X> source, Predicate<X> tester, Function <X, Y> mapper, Consumer<Y> block) { for (X p : source) {

if (tester.test(p)) { Y data = mapper.apply(p); block.accept(data);

} } } from http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Page 69: Lambdas and laughs   j1
Page 70: Lambdas and laughs   j1

MOAR!!!• Thinking in Functional Style [CON1767]

Monday 2:30 PM Hilton Yosemite B/C• Twins: FP and OOP [CON2159]

Monday 2:30 PM Hilton Continental 7/8/9• Loads more (insanely huge list for functional

programming)

Page 71: Lambdas and laughs   j1
Page 73: Lambdas and laughs   j1

Lambda JSR• http://jcp.org/en/jsr/detail?id=335

Articles on Lambdas• http://www.oraclejavamagazine-digital.com/javamagazine/20121112?pg=35#pg35• http://www.angelikalanger.com/Conferences/Slides/jf12_LambdasInJava8-1.pdf• http://datumedge.blogspot.com/2012/06/java-8-lambdas.html• http://www.infoq.com/articles/java-8-vs-scala

Presentations on Lambdas:• http://www.slideshare.net/ramonypp/java-8-project-lambda• http://www.slideshare.net/garthbrown/lambda-functions-in-java-8• http://www.angelikalanger.com/Conferences/Slides/jf12_LambdasInJava8-1.pdf

Lambda implementation mechanics:• http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html

Page 74: Lambdas and laughs   j1

Typical lambda use cases:• http://learnjavafx.typepad.com/weblog/2013/02/mary-had-a-little-%CE%BB.html• http://blueskyworkshop.com/topics/Java-Pages/lambda-expression-basics/• http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and

Defender method paper:• http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf

Method references (:: operator)• http://earthly-powers.blogspot.com/2012/07/java-8-lambda-and-method-references.html• http://doanduyhai.wordpress.com/2012/07/14/java-8-lambda-in-details-part-iii-method-and-constructor-referencing/• http://www.beyondjava.net/blog/are-java-8-method-references-going-to-be-more-important-than-lambdas/• http://www.lambdafaq.org/what-are-constructor-references/

Stream API:• http://cr.openjdk.java.net/~briangoetz/lambda/sotc3.html• http://aruld.info/java-8-this-aint-your-grandpas-java/• http://java.dzone.com/articles/exciting-ideas-java-8-streams

Sophisticated Lambda use case allowing for avoiding NPEs using Monads:• http://java.dzone.com/articles/no-more-excuses-use-null

Functional programming in Java• http://code.google.com/p/functionaljava/• http://shop.oreilly.com/product/0636920021667.do• http://apocalisp.wordpress.com/2008/06/18/parallel-strategies-and-the-callable-monad/

Page 75: Lambdas and laughs   j1

Thank you!