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

Recitation 11 Lambdas ---anonymous functions- - PowerPoint Presentation

myesha-ticknor
myesha-ticknor . @myesha-ticknor
Follow
360 views
Uploaded On 2018-03-15

Recitation 11 Lambdas ---anonymous functions- - PPT Presentation

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 ID: 652449

integer list return strs list integer strs return public void java size int lists left anonymous jbutton lambdas sort

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Recitation 11 Lambdas ---anonymous fun..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Slide1

Recitation 11

Lambdas ---anonymous functions---Slide2

What are Lambdas?Lambda expressions are anonymous functions

They can be created without method declarations and without belonging to any classThey can be passed as arguments to functionsThey are useful!Introduced in Java 8Slide3

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. functionclass PaintGUI { JButton jb= new JButton(“example”); jb.addActionListener((e) -> { … });}

This is an anonymous function

aka a "

lamda

expression"Slide4

Another Example: Customizing Comparison

Java implements a class PriorityQueuenew PriorityQueue<E>() - uses compareTo

implemented by E

But what it you want to use a different order?

- reverse order

- case insensitivePriorityQueues’s constructor can take a Comparator! Slide5

Java 7: Anonymous Inner ClassGoal: 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 onceThis is clunky!Old JavaSlide6

With LambdasOnly 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 onceparametersarrowexpression

Java takes care of turning this lambda into a ComparatorIntegerIntegerSlide7

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( );}Slide8

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));}Slide9

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);

d.add(t); }); return d;}blockbracesSlide10

More Complex LambdasList<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); return left.size() – right.size();});The lambda’s block can return values!Slide11

Try it Out/** Remove any non-increasing

lists. */public void filter(List<List<Integer>> lists) {}Slide12

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; });}Slide13

Lambda vs. Anonymous ClassesIn 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 Slide14

Difference: FieldsAnonymous 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; } });}Slide15

Difference: thisclass Foo {

void bar() { baz(new Anon() { Object func() { return this; }

});

}

}

class Foo { void bar() {

baz(() -> this); }}

Watch out!!!