Programming II Object Oriented Programming with Java - Advanced Topics - Java 8: Functional Interfaces, Method References and Lambda Expressions Alastair.

Slides:



Advertisements
Similar presentations
CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
Advertisements

Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
BUILDING JAVA PROGRAMS CHAPTER 7 Array Algorithms.
Lecture 2: Design and Implementation of Lambda Expressions in Java 8 Alfred V. Aho CS E6998-1: Advanced Topics in Programming Languages.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Computer Science 209 The Strategy Pattern II: Emulating Higher-Order Functions.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Array.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Interfaces. –An interface describes a set of methods: no constructors no instance variables –The interface must be implemented by some class. 646 java.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Programming in Java CSCI-2220 Object Oriented Programming.
CSC 142 Computer Science II Zhen Jiang West Chester University
Session 7 Methods Strings Constructors this Inheritance.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Classes - Intermediate
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
OOP Basics Classes & Methods (c) IDMS/SQL News
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Functional Processing of Collections (Advanced) 6.0.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Java Methods and Applications CSIS 3701: Advanced Object Oriented Programming.
Taking Java from purely OOP by adding “functional level Programming”
Generics, Lambdas, Reflections
Java Algorithms.
HKCT Java OOP Unit 02 Object Oriented Programming in Java Unit 02 Methods, Classes, and Objects 1.
Functional Programming with Java
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Interface.
Type & Typeclass Syntax in function
Generics, Lambdas, Reflections
„Lambda expressions, Optional”
Generics, Lambdas and Reflection
Presentation transcript:

Programming II Object Oriented Programming with Java - Advanced Topics - Java 8: Functional Interfaces, Method References and Lambda Expressions Alastair Donaldson

2 Remember good old map from Haskell? map :: (a -> b) -> [a] -> [b] Prelude> map (\x -> 10*x) [0..9] [0,10,20,30,40,50,60,70,80,90] Prelude> map (\x -> 1.0*x) [0..9] [0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0] Prelude> map (\x -> [x-1, x, x+1]) [0..9] [[-1,0,1],[0,1,2],[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7], [6,7,8],[7,8,9],[8,9,10]] Let’s try to do this in Java Multiply each list element by 10 Convert each list element to a float Raise list element x to a three-element list [x-1, x, x + 1]

3 Attempt 1: three separate loops public class JustLoops { public static void main(String[] args) { List integers = new ArrayList (); for(int i = 0; i < 10; i++) { integers.add(i); } List tenTimesBigger = new ArrayList (); for(Integer i : integers) { tenTimesBigger.add(10*i); } System.out.println(tenTimesBigger); List floats = new ArrayList (); for(Integer i : integers) { floats.add(new Float(i)); } System.out.println(floats); Make the list [0..9] Multiply elements by ten Turn elements into floats

4 Attempt 1: three separate loops... List > triples = new ArrayList<>(); for(Integer i : integers) { triples.add(Arrays.asList(new Integer[] { i-1, i, i+1 })); } System.out.println(triples); } } Raise each element to a triple [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] [[-1, 0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]] Program output:

5 Critique of Attempt 1 Produces the same effect as the Haskell program …but the map logic is re-implemented each time Not satisfactory

6 Attempt 2: a Transformer interface Haskell’s map takes a function that transforms something of type a into something of type b : map :: (a -> b) -> [a] -> [b] Let’s write map in Java, in terms of an interface that can transform something of type a into something of type b …but we’re in Java mode, so we’ll use S and T, not a and b

7 Transformer interface public interface Transformer { public T transform(S x); } Let us write our three transformers The interface is generic with respect to types S and T transform says: “give me an S and I will give you back a T

8 Three Transformer implementations public class TimesTenTransformer implements Transformer public Integer transform(Integer x) { return x*10; } public class IntegerToFloatTransformer implements Transformer public Float transform(Integer x) { return new Float(x); } public class IntegerToTripleTransformer implements Transformer > public List transform(Integer x) { return Arrays.asList(new Integer[] { x - 1, x, x + 1 }); } Notice here that we provide concrete types for S and T when we implement Transformer

9 Implementing map using the Transformer interface public interface Transformer { public T transform(S x); public static List map(Transformer transformer, List input) { List result = new ArrayList<>(); for(A a : input) { result.add(transformer.transform(a)); } return result; } } In Java 8, an interface can have static methods This is good, because sometimes an interface is the most logical home for such a method Our map method is not specific to any particular transformer, so it makes sense for it to live in the interface

10 Using map with our transformers public class UsingInterfaces { public static void main(String[] args) { List integers = new ArrayList (); for(int i = 0; i < 10; i++) { integers.add(i); } List tenTimesBigger = Transformer.map( new TimesTenTransformer(), integers); System.out.println(tenTimesBigger); List floats = Transformer.map( new IntegerToFloatTransformer(), integers); System.out.println(floats); List > triples = Transformer.map( new IntegerToTripleTransformer(), integers); System.out.println(triples); } }

11 Critique of approach 2 We succeeded in capturing the essence of map Generics played a nice role in making this work Painful: writing a separate class each time we need a transformer. Especially if we need a simple transformer and we only need it once

12 Approach 3: anonymous classes Instead of declaring TimesTenTransformer as a class: public class TimesTenTransformer implements Transformer public Integer transform(Integer x) { return x*10; } …and then using this class: List tenTimesBigger = Transformer.map( new TimesTenTransformer(), integers); …we can declare the class at the point we wish to use it. We don’t even need to give the class a name: it can be anonymous

13 An anonymous version of TenTimesTransformer This declares a nameless class that implements the Transformer interface, and creates a single instance of this class List tenTimesBigger = Transformer.map( new Transformer () public Integer transform(Integer x) { return x*10; } }, integers);

14 An anonymous version of IntegerToFloatTransformer Says: “Make an instance of a class that implements the Transformer interface, by defining the transform method as follows…” List floats = Transformer.map( new Transformer () public Float transform(Integer x) { return new Float(x); } }, integers);

15 An anonymous version of IntegerToTripleTransformer Similar: List > triples = Transformer.map( new Transformer >() public List transform(Integer x) { return Arrays.asList(new Integer[] { x - 1, x, x + 1 }); } }, integers);

16 Critique of approach 3 Arguably less painful than approach 2: we did not have to write a separate class file for each transformer. Instead we described the transformers “on demand” using anonymous classes. But the anonymous class syntax is pretty verbose!

17 Functional interfaces An interface is a functional interface if it declares exactly one abstract method. To implement a functional interface, a class just needs to provide the single abstract method. Transformer is a functional interface: - One abstract method: transform - Also one non-abstract, static method, map

18 Functional interfaces and method references Suppose a method expects a parameter of type I, where I is a functional interface. In Java 8: - Instead of passing an instance of a class that implements I … - …you can pass a method that matches the signature of the single abstract method associated with the functional interface

19 Approach 4: use method references map expects a Transformer as its first argument Transformer is a functional interface Instead of passing a Transformer to map, we can pass any method that: - accepts a single argument of type S - returns something of type T

20 Passing timesTen as a method reference public class UsingMethodReferences { private static Integer timesTen(Integer x) { return x * 10; } public static void main(String[] args) { List integers =...; List tenTimesBigger = Transformer.map( UsingMethodReferences::timesTen, integers); System.out.println(tenTimesBigger); } } Write UsingMethodReferences::timesTen to refer to static method timesTen of UsingMethodReferences class There is also syntax for getting a reference to an instance method of an object (look it up)

21 Passing toTriple as a method reference public class UsingMethodReferences { private static List toTriple(Integer x) { return Arrays.asList(new Integer[] { x - 1, x, x + 1 }); } public static void main(String[] args) { List integers =...; List > triples = Transformer.map( UsingMethodReferences::toTriple, integers); System.out.println(triples); } } Method reference

22 Passing Float constructor as a method reference public class UsingMethodReferences { public static void main(String[] args) { List integers =...; List floats = Transformer.map( Float::new, integers); System.out.println(floats); } } Float::new is a reference to the constructor Float(Integer x) Type inference is used to determine which constructor makes sense here

23 Critique of approach 4 Passing in Float::new as a method reference is pretty neat! It’s not clear that passing in timesTen and toTriple as method references is worth it. They do such simple things; it’s annoying to have to write a specially named method for each of them.

24 Functional interfaces and lambda expressions Suppose a method expects a parameter of type I, where I is a functional interface. In Java 8, instead of passing an instance of a class that implements I, or a method reference, you can pass in a lambda expression. A lambda expression describes a function that produces a result from some arguments.

25 Lambda expression: example Instead of passing map a reference to the timesTen method: we can instead pass a lambda expression: Means we do not have to define timesTen at all! List tenTimesBigger = Transformer.map( UsingMethodReferences::timesTen, integers); List tenTimesBigger = Transformer.map(x -> x*10, integers); Compactly describes a function which, given argument x, returns x*10 The term “lambda” comes from the Lambda Calculus

26 Approach 5: use lambdas public class UsingLambdas { public static void main(String[] args) { List integers =... List tenTimesBigger = Transformer.map( x -> x*10, integers); System.out.println(tenTimesBigger); List floats = Transformer.map( Float::new, integers); System.out.println(floats); List > triples = Transformer.map( x -> Arrays.asList(new Integer[] { x - 1, x, x + 1 }), integers); System.out.println(triples); } } These are lambda expressions

27 Critique of approach 5 Basically gives us the elegance of map in Haskell, but in Java.

28 Let’s write a method to compose two transformers public static Transformer compose( Transformer t1, Transformer t2) { return (x -> t2.transform(t1.transform(x))); } Input: a transformer from S to T, a transformer from T to U Output: the transformer from S to U obtained by composing the input transformers Here we are returning a lambda expression. The caller of compose can then apply the lambda expression in the future

29 Composition in action public class Composition { public static Transformer compose( Transformer t1, Transformer t2) { return (x -> t2.transform(t1.transform(x))); } public static void main(String[] args) { List integers =...; Transformer > timesTenAndTriple = compose((x -> x*10), (x -> Arrays.asList(new Integer[] { x - 1, x, x + 1 })) ); List > bigTriples = Transformer.map(timesTenAndTriple, integers); System.out.println(bigTriples); } } Stores a reference to a lambda expression The stored lambda expression is applied

30 Composition in action Output: [[-1, 0, 1], [9, 10, 11], [19, 20, 21], [29, 30, 31], [39, 40, 41], [49, 50, 51], [59, 60, 61], [69, 70, 71], [79, 80, 81], [89, 90, 91]]

31 Summary Anonymous classes avoid the need to declare a named class when only a simple activity is required. A functional interface can be implemented in a more light-weight manner: by passing a method reference for the single abstract method. A lambda expression can be used in place of a method reference, leading to very concise code Take home message: none of this lets you do anything you could not already do. It simply allows more elegant and concise code

32 Next time A few more details about anonymous classes A discussion of default methods (a.k.a. defender methods) in Java 8.