Lambdas and Laughs Jim Bethancourt Houston

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Object Oriented Programming with Java
COSC 2006 Data Structures I Instructor: S. Xu URL:
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Java 8 Feature Preview Mostly about Lambdas. New Feature Overview Roughly 50 new features Worth mentioning – Concurrency updates (possible STM support)
DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Java Review Interface, Casting, Generics, Iterator.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Written by: Dr. JJ Shepherd
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
COMS S1007 Object-Oriented Programming and Design in Java August 7, 2007.
Java Course Outline Kumar Harshit, USW. Course Description Teaches students to program using the Java programming language with the help of the Netbeans.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Chapter 17 Java SE 8 Lambdas and Streams
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Programming Languages and Paradigms Object-Oriented Programming.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Effective Java: Generics Last Updated: Spring 2009.
Java Introduction 密碼學與應用 海洋大學資訊工程系 丁培毅.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java8 Released: March 18, Lambda Expressions.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Functional Processing of Collections (Advanced) 6.0.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lecture 5:Interfaces and Abstract Classes
Modern Programming Tools And Techniques-I
Taking Java from purely OOP by adding “functional level Programming”
Inheritance and Polymorphism
Functional Processing of Collections (Advanced)
Java Algorithms.
Functional Programming with Java
Java 8 Java 8 is the biggest change to Java since the inception of the language Lambdas are the most important new addition Java is playing catch-up: most.
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Conditional Statements
COS 260 DAY 10 Tony Gauvin.
Java Inheritance.
A few of the more significant changes and additions. James Brucker
Abstract Classes and Interfaces
Lambda Expressions.
Chapter 11 Inheritance and Polymorphism Part 1
Corresponds with Chapter 5
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Lambdas and Laughs Jim Bethancourt Houston

Forward Looking Statement Ok, Not Really…

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

Download Links & IDE Support Regular JDK download link (for EAs) Netbeans IntelliJ Eclipse

Maven Support org.apache.maven.plugins maven-compiler-plugin

Lambdas A 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");

Lambdas Blocks: (x, y, z) -> { if (x==y) return x; else { int result = y; for (int i = 1; i < z; i++) result *= i; return result; }}

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

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

MOAR!!! Thursday Lambda Programming Laboratory [HOL3373] 2 PM Hilton Franciscan A/B Lambda-izing JavaFX [CON3248] 3:30 PM Hilton Plaza A

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

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

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 }}

Specify the Parent Interface interface 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}}

Convert Anonymous Class to Lambda from // Anonymous inner class for event handling.onAction(new EventHandler () public void handle(ActionEvent e) { anim.playFromStart(); } })

Convert Anonymous Class to Lambda.onAction((ActionEvent) -> { anim.playFromStart(); } }).onAction((e) -> {anim.playFromStart();})

Convert Anonymous Class to Lambda.onAction((ActionEvent) -> { anim.playFromStart(); } }).onAction((e) -> {anim.playFromStart();}).onAction(e -> { anim.playFromStart(); }).onAction(e -> anim.playFromStart();)

MOAR!!! Transforming Code to Java 8 [CON1772] Thursday 2:30 Hilton Imperial B

forEach forEach() - available on Iterator & Map interfaces and their implementations Allows for internal control of iteration of elements for possible parallel operation List names = Arrays.asList(“Bill", “Ed", “Al"); names.forEach(e -> { System.out.println(e); }); But be careful!!!

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

java.util.stream Classes to support functional-style operations on streams of values Stream - A sequence of elements supporting sequential and parallel bulk ops

java.util.stream Stream opened by calling – Collection.stream() – Collection.parallelStream() List names = Arrays.asList("Bill", “Ed", “Al"); out(names.stream().filter(e -> e.length() >= 4 ).findFirst().get()); Returns “Bill”

java.util.stream All other interfaces in stream package accessible through Stream interface Collector - A (possibly parallel) reduction operation. FlatMapper - Maps element of type T to zero or more elements of type U.

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!!!

java.util Spliterator provides traversal operations Optional – Returned by Stream’s aggregate methods find*(), reduce(), min(), max() – Call get() to get the value it’s holding

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

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

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

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

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

Use a Method Reference This bttnExit.setOnAction( (actionEvent) -> { try { stop(); } catch (Exception e) { // TODO: add error handling } }); Can be bttnExit.setOnAction( this::onExitButtonClick);... void onExitButtonClick() { try { stop(); } catch (Exception e) { // TODO: add error handling }

Use a Constructor Reference interface Factory { T make(); } Factory > f1 = ArrayList:: new; Every time make() is invoked, it will return a new ArrayList

How many times have you heard

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) {}}}

Functional Interface Has just one abstract method. (Can have other methods with bodies) Represents a functional contract. annotation helps ensure the Functional Interface contract is honored

Functional Interface What happens when you have more than one abstract method &

java.util.function Functional interfaces provide target types for lambda expressions and method references Consumer Function Supplier Predicate Unary/BinaryOperator Bi(Consumer/Function/Predicate)

public static void processElements( Iterable source, Predicate tester, Function mapper, Consumer block) { for (X p : source) { if (tester.test(p)) { Y data = mapper.apply(p); block.accept(data); } } } from

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)

New Java 8 Feature Overview far-sight-look-jdk-8 far-sight-look-jdk-8 Java 8 Maven Support 12/08/java-lambda-support-in-java-8.html 12/08/java-lambda-support-in-java-8.html

Lambda JSR Articles on Lambdas Presentations on Lambdas: Lambda implementation mechanics:

Typical lambda use cases: Defender method paper: Method references (:: operator) Stream API: Sophisticated Lambda use case allowing for avoiding NPEs using Monads: Functional programming in Java

Thank you!