Lambdas ---anonymous functions---

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Inner Classes. Nested Classes  An nested class is a class that is defined inside another class.  To this point we have only studied top-level classes.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Introduction to Computers and Programming Midterm Review Sana Odeh.
CS102 Data Types in Java CS 102 Java’s Central Casting.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
Applications Development
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
2-Dec-15 Inner Classes. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside another class.
CS 261 – Data Structures Introduction to C Programming.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Repetition Statements
Programming with Recursion
CS314 – Section 5 Recitation 9
Lecture 15.1 Event Delegation.
Modular Event Handling
Inner Classes.
Inner Classes 27-Dec-17.
Information and Computer Sciences University of Hawaii, Manoa
Object-Oriented Concepts
Arrays Chapter 7.
Recitation 11 Lambdas added to Java 8.
Debugging and Random Numbers
Generics, Lambdas, Reflections
Nested class.
Programming with Recursion
Functional Programming with Java
Inner Classes 11/14/ Dec-04 inner_classes.ppt.
Lesson 2: Building Blocks of Programming
Object Oriented Programming (OOP) LAB # 8
Anonymous Classes A short-cut for defining classes when you want to create only one object of the class.
Java Programming Language
Conditional Statements
Built-In (a.k.a. Native) Types in C++
Fall 2018 CISC124 12/3/2018 CISC124 or talk to your grader with questions about assignment grading. Fall 2018 CISC124 - Prof. McLeod Prof. Alan McLeod.
Object Oriented Programming in java
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Functional interface.
Arrays Chapter 7.
Recap Week 2 and 3.
Simple Classes in Java CSCI 392 Classes – Part 1.
Type Safety, Generics, Lambdas, Class Object
Effective Java, 3rd Edition Chapter 7: Lambdas and Streams
Namespaces, Scopes, Access privileges
Homework Any Questions?.
A few of the more significant changes and additions. James Brucker
Barb Ericson Georgia Institute of Technology June 2005
Generics, Lambdas, Reflections
Inner Classes 17-Apr-19.
Inner Classes 21-Apr-19.
Chapter 18 Recursion.
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Review for Midterm 3.
First Semester Review.
„Lambda expressions, Optional”
Inner Classes.
Corresponds with Chapter 5
...that can get messy when we have lots buttons!
Functions John R. Woodward.
Chengyu Sun California State University, Los Angeles
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
Inner Classes 25-Oct-19.
Presentation transcript:

Lambdas ---anonymous functions--- Recitation 11 Lambdas ---anonymous functions---

What are Lambdas? Lambda expressions are anonymous functions They can be created without method declarations and without belonging to any class They can be passed as arguments to functions They are useful! Introduced in Java 8

Why Lambdas? JButton jb= new JButton(“example”); jb.addActionListener(function_to_call); Java 7: Argument must be an object class PaintGUI implements ActionListener { JButton jb= new JButton(“example”); jb.addActionListener(this); @override public void actionPerformed(ActionEvent e){ Object s = e.getSource(); if(s == pencil){ … } if(s == jb){ … } … } Java 8: Argument can be anon. function class PaintGUI { JButton jb= new JButton(“example”); jb.addActionListener((e) -> { … }); } This is an anonymous function aka a "lamda expression" Example is drawn from a5, so they should have seen it before. Action listeners really should take functions as arguments (what do do when an event occurs), but without lambdas they can't. The skeleton code for a5 works around this by having class paintGUI implement ActionListener (by implementing method actionPerformed) and passing this as the argument to addActionListener. With Lambdas, we can have much cleaner code. Pass the action handling function directly to to addActionListener. No long case statements. No awkward private or anonymous classes.

Another Example: Customizing Comparison Java implements a class PriorityQueue new PriorityQueue<E>() - uses compareTo implemented by E But what it you want to use a different order? - reverse order - case insensitive PriorityQueues’s constructor can take a Comparator!

Java 7: Anonymous Inner Class Goal: sort non-negative integers modulo n int n = …; // > 0 … = new PriorityQueue<Integer>( new Comparator<Integer>() { public int compare(Integer x, Integer y) { return x % n – y % n; } }); Can access variables that are assigned to exactly once This is clunky! Old Java

With Lambdas Only one abstract method to implement, so we can use a lambda! int n = …; // > 0 … = new PriorityQueue<Integer>( ( x, y) -> x % n – y % n ); Can still access variables that are assigned to exactly once Integer Integer At this point, go over the syntax of a lambda expression Note: Parameter types are optional, but often they should be included for readability. Note: Parentheses are optional when there’s only one parameter. parameters arrow expression Java takes care of turning this lambda into a Comparator

Try it Out /** Print out the lower-cased versions of the * non-empty strings in strs in order of length. */ public void practice(List<String> strs) { // no loops! strs.removeIf( ); strs.replaceAll( ); strs.sort( ); strs.forEach( ); } Do the first one together. Have them figure out the rest. Show them the javadoc for these methods and the associated interfaces. Show java.util.function.

Answer /** Print out the lower-cased versions of the * non-empty strings in strs in order of length. */ public void practice(List<String> strs) { // no loops! strs.removeIf(s -> s.isEmpty()); strs.replaceAll(s -> s.toLowerCase()); strs.sort((s1, s2) -> s1.length() – s2.length()); strs.forEach(s -> System.out.println(s)); }

More Complex Lambdas /** Maps [a, b, c] to [a, a, b, b, c, c] */ public <T> List<T> doubleList(List<T> list) { List<T> d = new ArrayList<T>(); list.forEach(t -> { d.add(t); }); return d; } block braces

The lambda’s block can return values! More Complex Lambdas List<List<Integer>> lists = …; // no nulls // sort so that [1, 3] is before [2, 4, 5] lists.sort((List<Integer> left, List<Integer> right) -> { if (left.size() > right.size()) return left.size() – right.size(); for (int i = 0; i; < left.size(); i++) if (left.get(i) > right.get(i)) return left.get(i) – right.get(i); }); The lambda’s block can return values! note that this lambda is a comparison function (like compareTo); review the spec for that

Try it Out /** Remove any non-increasing lists. */ public void filter(List<List<Integer>> lists) { } Have them figure this out.

Answer /** Remove any non-increasing lists. */ public void filter(List<List<Integer>> lists) { lists.removeIf((List<Integer> list) -> { int prev = Integer.MIN_VALUE; for (int i : list) // Ignoring nulls  if (prev > i) return true; else prev = i; return false; }); }

Lambda vs. Anonymous Classes In many ways, lambda expressions are really just cleaner syntax The Java compiler converts lambdas into anonymous classes at compile time. Two key differences: - fields - this

Difference: Fields Anonymous classes can have fields /** Maps [3, 4, 5] to [3, 7, 12] */ public void sumPrev(List<Integer> ints) { ints.replaceAll(new UnaryOperator<Integer>() { int sum = 0; public Integer apply(Integer i) { sum += i; return sum; } }); lambda functions are just one method, no fields

Watch out!!! Difference: this class Foo { void bar() { baz(new Anon() { Object func() { return this; } }); class Foo { void bar() { baz(() -> this); } Watch out!!!