SlideShare una empresa de Scribd logo
1 de 69
Descargar para leer sin conexión
Java 8
Lambda
Expressions
Angelika Langer
Training/Consulting
http://www.AngelikaLanger.com/
objective

•
•
•
•
•

explain the new language feature of lambda expressions
what is the intent?
which problem do they solve?
what are the syntax elements?
how will they be used in the JDK?

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(2)
speaker's relationship to topic

• independent trainer / consultant / author
–
–
–
–
–

teaching C++ and Java for 15+ years
curriculum of a couple of challenging courses
co-author of "Effective Java" column
author of Java Generics FAQ online
JCP member and Java champion since 2005

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(3)
agenda

•
•
•
•
•
•

introduction
functional interfaces
lambda expressions (the details)
method references
extension methods
‘lambdafication’ of the JDK

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(4)
lambda expressions in Java

• lambda expressions
– aka lambdas; formerly known as closures

• concept from functional programming
– “anonymous method” / “code-as-data”
‘ad hoc’ implementation of functionality
 pass functionality around (parameter, return value)


– similar to (anonymous) inner classes


advantage of lambda expressions: concise syntax + less code

“more functional”



© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(5)
history

• 2006 – 2009
– several proposals for ‘closures in Java’

– no convergence; none fully supported by Sun / Oracle

• since 2010
– OpenJDK Project Lambda; tech lead Brian Goetz

– JSR 335 (Nov. 2010)
"Lambda Expressions for the Java Programming Language"

– JEP 126 (Nov. 2011)
"Lambda Expressions and Virtual Extension Methods"

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(6)
Oracle’s design guideline

• aid usage of libraries that …
– make use of parallelization on multi core platforms
– special focus: JDK

• rules out
– which features are relevant?
– how complex can they be?

• general guideline: "as simple as possible"
– several (previously discussed) features were dropped
– e.g. function types, exception transparency, …

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(7)
agenda

•
•
•
•
•
•

introduction
functional interfaces
lambda expressions (the details)
method references
extension methods
‘lambdafication’ of the JDK

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(8)
key goal

• support JDK abstractions that …
– make use of parallelization on multi core platforms

• collections shall have parallel bulk operations
– based on fork-join-framework (Java 7)
– execute functionality on a collection in parallel
i.e. access multiple elements simultaneously



– specified as: JEP 107


details later

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(9)
today
private static void checkBalance(List<Account> accList) {
for (Account a : accList)
if (a.balance() < threshold) a.alert();
}

• new for-loop style
– actually an external iterator object is used:
Iterator iter = accList.iterator();
while (iter.hasNext()) {
Account a = iter.next();
if (a.balance() < threshold) a.alert();
}

• code is inherently serial
– traversal logic is fixed
– iterate from beginning to end
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(10)
Stream.forEach() - definition

public interface Stream<T> ... {
...
void forEach(Block<? super T> sink);
...
}

public interface Block<A> {
void apply(A a);
…
}

• forEach()’s iteration is not inherently serial
– traversal order is defined by forEach()’s implementation
– burden of parallelization is put on the library developer


not on the library user

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(11)
Stream.forEach() - example
Stream<Account> pAccs = accList.parallel();
// with anonymous inner class
pAccs.forEach( new Block<Account>() {
void apply(Account a) {
if (a.balance() < threshold) a.alert();
}
} );
// with lambda expression
pAccs.forEach( (Account a) ->
{ if (a.balance() < threshold) a.alert(); } );

• lambda expression
– less code (overhead)
– only actual functionality


easier to read

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(12)
lambda expression a Block<Account> ?

Block<Account> block =
(Account a) -> { if (a.balance() < threshold) a.alert(); };

• right side: lambda expression
• intuitively
– ‘something functional’
takes an Account
 returns nothing (void)
 throws no checked exception


• nothing in terms of the Java type system
– just some code / functionality / implementation
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(13)
functional interface = target type of a lambda
interface Block<A> { public void apply(A a); }
Block<Account> pAccs =
(Account a) -> { if (a.balance() < threshold) a.alert(); };

• lambdas are converted to functional interfaces
– function interface ≈ interface with one method

– parameter type(s), return type, checked exception(s) must match
– functional interface’s name + method name are irrelevant

• conversion requires type inference

– lambdas may only appear where target type can be inferred from
enclosing context
– e.g. variable declaration, assignment, method/constructor arguments, return
statements, cast expression, …

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(14)
idea behind functional interfaces

• interfaces with one method have been the ‘most
functional things’ in Java already:
interface Runnable
interface Callable<T>
interface Comparator<T>
...

{ void run(); }
{ T call(); };
{ boolean compare(T x, T y); }

– "as simple as possible"

– reuse existing interface types as target types for lambda
expressions

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(15)
lambda expressions & functional interfaces

• functional interfaces
interface Block<A>
{ void apply(A a); }
interface MyInterface { void doWithAccount(Account a); }

• conversions
Block<Account> block =
(Account a) -> { if (a.balance() < threshold) a.alert(); };
MyInterface mi =
(Account a) -> { if (a.balance() < threshold) a.alert(); };
mi = block;

error: types are not compatible

• problems
error: cannot infer target type
Object o1 =
(Account a) -> { if (a.balance() < threshold) a.alert(); };

Object o2 = (Block<Account>)
(Account a) -> { if (a.balance() < threshold) a.alert(); };
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(16)
evaluation

• lambda expression
– easy and convenient way to implement ad-hoc functionality

• functional interfaces
– serve as target types for lambda expressions
– integrate lambda expressions into Java type system

• advantages
– simple: no new elements in Java type system


good for language designers and users

– built-in backward compatibility


e.g. can provide a lambda where a Runnable (JDK 1.0) is needed

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(17)
evaluation (cont.)

• down-side
– must define Block<A> to describe parameter type:
public void forEach(Block<? super T> sink) ...
public interface Block<A> { void apply(A A); }

– code overhead, no explicit function type: <T>->void

• justification: overhead is acceptable
– explicit function types add many more complications
– "we (the library providers) do it for you (the library users)"
– may be added later


JSR 335 (lambda spec) mentions function types as potential future enhancement

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(18)
agenda

•
•
•
•
•
•

introduction
functional interfaces
lambda expressions (the details)
method references
extension methods
‘lambdafication’ of the JDK

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(19)
lambda expression syntax

• since September 2011:
(Account a) -> { if (a.balance() < threshold) a.alert(); }

• previously:
# { Account a -> if (a.balance() < threshold) a.alert(); }

• syntax: C#, with ‘->’ instead of ‘=>’
– proven concept
– quite similar to Scala’s closure syntax, too
– ‘->’ instead of ‘=>’ to avoid dueling arrows
foo (x => x.size <= 10);
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(20)
formal description

lambda = ArgList "->" Body
ArgList = Identifier
| "(" Identifier [ "," Identifier ]* ")"
| "(" Type Identifier [ "," Type Identifier ]* ")“
Body = Expression
| "{" [ Statement ";" ]+ "}"

• options related to
– argument list, and
– body

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(21)
argument list, pt. 1
ArgList = Identifier
| "(" Identifier [ "," Identifier ]* ")"
| "(" Type Identifier [ "," Type Identifier ]* ")“
a -> { if (a.balance() < threshold) a.alert(); }
(a) -> { if (a.balance() < threshold) a.alert(); }
(Account a) -> { if (a.balance() < threshold) a.alert(); }

• if possible, compiler infers parameter type
– inference based on target type, not lambda body

• if not possible, parameter type must be specified
– parameter type can always be specified

• multiple parameters
– all parameters either declared or inferred (no mix possible)
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(22)
argument list, pt. 2
ArgList = Identifier | ...

• omission of parentheses in case of
one argument without type identifier possible
• examples:
a

-> { if (a.balance() < threshold) a.alert(); }

(int x) -> { return x+1; }
x -> { return x+1; }

// omit parentheses

(int x, int y) -> { return x+y; }
(x,y) -> { return x+y; } // can’t omit parentheses
// no special nilary syntax
() -> { System.out.println(“I am a Runnable”); }

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(23)
body
Body = Expression | "{" [ Statement ";" ]+ "}"

// single statement
a -> { if (a.balance() < threshold) a.alert(); }
// single expression
a -> (a.balance() < threshold) ? a.alert() : a.okay()
// list of statements
a -> {
Account tmp = null;
if (a.balance() < threshold) a.alert();
else tmp = a;
if (tmp != null) tmp.okay();
}

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(24)
return, pt. 1

()

-> { return 21; }

// returns int

(Account a) -> { return a; }

// returns Account

()

// returns long

-> { return (long)21; }

• return type is always inferred
– i.e. cannot be specified explicitly

– you might consider to cast the return value

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(25)
return, pt. 2
() -> { return 21; }
() -> return 21
() -> 21
error !!!

• no return with single expression
– use of return is an error

• return used with list of statements
– when using multiple returns:
programmer responsible, that the return type can be inferred

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(26)
local variable capture

int i = 16;
Runnable r = () -> { System.out.println(“i is: ” + i); };

• local variable capture
– important feature
– similar to anonymous inner classes
but no explicit final
 but still only read access


© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(27)
local variable capture (cont.)

int i = 16;
Runnable r = () -> { System.out.println(“i is: ” + i); };
i++;
error
because

• effectively final variables
– same as with anonymous inner classes, but


you do not have to use the final identifier explicitly

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(28)
effectively final

• local variable capture not much different from inner
classes
• but caused a lot of discussion
– I want write access !

• a look at the details
– shows the limitations

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(29)
reason for effectively final
int i = 0;
Runnable r =
() -> { for (int j=0; j < 32; j++ ) i = j; };
// start Runnable r in another thread
...
error

while (i <= 16) /* NOP */;
System.out.println(“i is now greater than 16”);

• problem: unsynchronized concurrent access
• no guaranties from the memory model
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(30)
but the effectively final does not prevent …

… all evil in the world
• consider a mutable object referred to by an effectively
final reference
int[] ia = new int[1];
Runnable r =
() -> { for (int j==; j < 32; j++ ) ia[0] = j); };
// start Runnable r in another thread
...
while (ia[0] <= 16) /* NOP */;
System.out.println(“ia[0] is now greater than 16”);
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(31)
I want write access ! – idioms to come ?
File myDir = ....
int[] ia = new int[1];
File[] fs = myDir.listFiles( f -> {
if (f.isFile() {
n = f.getName();
if (n.lastIndexOf(“.exe”) == n.length()-4)
ia[0]++;
return true;
}
return false;
};);
System.out.println("contains " + fs.size + "files, " +
ia[0] + "are exe-files");

• no problem, if everything is executed sequentially
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(32)
no transparent parallelism !
int[] ia = new int[1];
pAccs.forEach( (Account a) -> {
if (a.balance() < threshold) {
a.alert();
ia[0]++;
}
} );
System.out.println(ia[0] + " alerts !!!");

• need to know whether …
– methods that take lambda uses multiple threads or not
– Stream.forEach() vs. File.list()

• currently not expressed in Java syntax
– JavaDoc, comment, …
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(33)
lambda body lexically scoped, pt. 1

• lambda body scoped in enclosing method
• effect on local variables:
– capture works as shown before
– no shadowing of lexical scope

lambda

int i = 16;
Runnable r = () -> { int i = 0;
System.out.println(“i is: ” + i); };

error

• different from inner classes
– inner class body is a scope of its own

inner class

final int i = 16;
Runnable r = new Runnable() {
public void run() { int i = 0;
System.out.println(“i is: ” + i); }
};
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

fine

Lambda Expressions in Java

(34)
lambda body lexically scoped, pt. 2
• this

refers to the enclosing object, not the lambda

– due to lexical scope, unlike with inner classes

lambda

public class MyClass {
private int i=100;

}

public void foo() {
...
Runnable r = () -> {System.out.println(“i is: “ + this.i);};
...
}

inner class
public class MyClass {
private int i=100;
public void foo() {
...
Runnable r = new Runnable() {
private int i=200;
public void run() {System.out.println(“i is: “ + this.i);}
};
...
} }
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(35)
lambdas vs. inner classes - differences

• local variable capture:

– implicitly final vs. explicitly final

• different scoping:

– this means different things

• verbosity:

– concise lambda syntax vs. inner classes' syntax overhead

• performance:

– lambdas slightly faster (use MethodHandle from JSR 292 ("invokedynamic"))

• bottom line:

– lambdas better than inner classes for functional types

• but what if you add a second method to a functional interface
– and turn it into a regular non-functional type ???

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(37)
agenda

•
•
•
•
•
•

introduction
functional interfaces
lambda expressions (the details)
method references
extension methods
‘lambdafication’ of the JDK

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(38)
an example

• want to sort a collection of Person objects
– using the JDK's new function-style bulk operations and
– a method from class Person for the sorting order
element type Person
class Person {
private final String name;
private final int age;
…
public static int compareByName(Person a, Person b) { … }
}

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(39)
example (cont.)
• Stream<T> has a sorted() method
Stream<T> sorted(Comparator<? super T> comp)

• interface Comparator is a functional interface
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}

inherited from Object

• sort a collection/array of Persons
Stream<Person> psp = Arrays.parallel(personArray);
…
psp.sorted((Person a, Person b) -> Person.compareByName(a,b));
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(40)
example (cont.)

• used a wrapper that invokes compareByName()
psp.sorted((Person a, Person b) -> Person.compareByName(a,b));

• specify compareByName() directly (method reference)
psp.sorted(Person::compareByName);

– reuse existing implementation
– less code

• syntax not final, but very likely: “::”

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(41)
idea …

… behind method references
• take an existing method from some class, and
make it the implementation of a functional interface
– similar to lambda expressions

• need context that allows conversion to a target type
– similar to lambda expressions

• method handles are included in JSR 335

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(42)
agenda

•
•
•
•
•
•

introduction
functional interfaces
lambda expressions (the details)
method references
extension methods
‘lambdafication’ of the JDK

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(43)
problem

• no (good) support for interface evolution in Java today
• interface evolution
= add a new method to an existing interface
– problem: all existing implementations of the interface break

• concrete situation
– extend existing collection interfaces for functional programming
– e.g. to interface java.util.Collection<T> add method:
void forEach(Block<? super T> block)

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(44)
solution

• extension method
– add a new method to an interface together
with a default implementation
– implementations of the interface are free to override it,
but don’t have to

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(45)
example
from package java.util:
public interface Collection<T>
extends … {
... everything as before ...

}

public void forEach(Block<? super T> block)
default {
for (T each : this)
block.apply(each);
}
...

• no additional state / no instance fields
• implementation based on the functionality of the other methods +
the additional parameter(s) from the new method

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(46)
notes

• extension methods are included in JSR 335
• name:
– also know as: defender methods and default methods
– in JSR 335 called virtual extension methods


as opposed to C#'s (non-virtual) extension methods
(which cannot be overridden)

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(47)
extensions methods vs. OO concepts

• Java interfaces are not really interfaces anymore
• they (can) provide implementation
• dilutes the "interface" concept somewhat

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(48)
extensions methods vs. OO concepts

• Java provides multiple inheritance of functionality now
class A extends B implements I, J, K, L {}

– A inherits functionality from B
– A might inherit functionality from I, J, K, L
because these interfaces might provide extensions methods

• is it a problem ? - NO !
– relatively safe, no additional state inherited from interfaces

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(49)
language evolution
C++:
• multiple inheritance of functionality
– considered dangerous

classic Java:
• single inheritance of functionality + multiple inheritance only for
interfaces
– problem: interface evolution => where to provide new functionality ?

new languages:
• mixins (Ruby) / traits (Scala)
– to solve the problem

Java 8:
• extension methods

– fit into existing language
– not too different from ‘stateless’ traits in Scala
(but without linearization to resolve defaults)

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(50)
problem with multiple inheritance

the diamond:

A
B

C
D

• how is A’s state inherited to D ?
– once, or
– twice (via B and via C)

• there is no ‘right’ answer to this question
– C++ gives you the option: virtual / non-virtual inheritance
– makes it more complicated

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(51)
Java 8

the diamond:

A
B

C
D

• A can only be an interface (not a class)
– can have an implementation, but
– no state (no instance fields)

• no state means no (diamond) problem !
– no issue regarding "how many A parts does D have ?"

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(52)
still conflicts – ambiguity #1

• inherit the same method from
a class and an interfaces
– extends dominates implements

– sub-class inherits super-class’s method (not interface’s method)
I

foo() default { … }

C1

C2

foo() { … }

inherits foo() from C1

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(53)
ambiguity #2

• inherit the same method from different interfaces
– sub-interfaces shadow super-interfaces
– if the interfaces are unrelated -> no default at all


I1

results in a compile error

foo() default { … }

I1

foo() default { … }

I2
I2
C

foo() default { … }

foo() default { … }

inherits foo() from I2

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

C

compile-time error !

Lambda Expressions in Java

(54)
ambiguity #2 (cont.)

• can address ambiguity explicitly
when implementing class C

I1

foo() default { … }

I2

foo() default { … }

C
class C implements I1, I2 {
public void foo() { I1.super.foo(); }
}

– new syntax to qualify the super-interface

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(55)
implementation techniques in collection framework

• until now:
– interfaces for types
– skeletal behavior with abstract classes
interfaces

abstract classes

concrete classes

Iterable<E>
Collection<E>
List<E>

AbstractCollection<E>
AbstractList<E>

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

ArrayList<E>

Lambda Expressions in Java

(57)
beyond interface evolution

• interface evolution is primary motivation,
but extension methods are useful in themselves
• approach:
– define interface as always
– provide default implementation for those methods that …
don’t need state, but
 can be based on functionality of other (really abstract) methods


– provide implementation of (really abstract) methods
by abstract classes (if functionality can be factored out)
 by concrete classes


© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(58)
extension methods and retrofits

• JDK 1.0 introduced Enumeration
• JDK 1.2 replaced it with Iterator
• conceivable in Java 8
interface Enumeration<E> extends Iterator<E> {
boolean hasMoreElements();
E nextElement();

}

boolean hasNext()
E next()
void remove()
throw
}

default { return hasMoreElements(); }
default { return nextElement(); }
default {
new UnsupportedOperationException();

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(59)
agenda

•
•
•
•
•
•

introduction
functional interfaces
lambda expressions (the details)
method references
extension methods
‘lambdafication’ of the JDK

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(60)
JEP 107: Bulk Data Operations for Collections

• JEP = JDK enhancement proposal, for Java 8
• also know as: "for-each/filter/map/reduce for Java"
– for-each
apply a certain functionality to each element of the collection
accountCol.forEach(a -> a.addInterest());

– filter
build a new collection that is the result of a filter applied to each
element in the original collection
Stream<Account> result =
accountCol.filter(a -> a.balance() > 1000000 ? true:false);
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(61)
JEP 107 (cont.)
– map
build a new collection, where each element is the result of a
mapping from an element of the original collection
Stream<Integer> result =
accountCol.map(a -> a.balance());

– reduce
produce a single result from all elements of the collection
accountCol.map(a -> a.balance())
.reduce(new Integer(0),
(b1, b2) -> new Integer(b1.intValue()+b2.intValue()));

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(62)
JEP 107 (cont.)

… additional methods
• sorted(), anyMatch(), findFirst(), …
– see JavaDoc for yourself

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(63)
serial vs. parallel & eager vs. lazy

• provides
– serial processing, i.e. performed by single thread
– parallel processing, i.e. using multiple parallel threads

• provides
– eager processing, i.e. produce a result or side effect
– lazy processing, i.e. creates a stream

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(64)
eager vs. lazy - example
• consider a sequence of operations
– filter with a predicate, map to long value, and apply printing
myCol.filter((Account a) -> a.balance() > 1000000)
.map((Account a) -> a.balance())
.forEach((long l) -> System.out.format("%dt",l));

• eager
– each operation is executed when it is applied

• lazy
– execute everything after the last operation has been applied
– optimize this execution
e.g. call a.balance() only once for each account and
print it directly without any intermediate collection of balances



© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(65)
streams

• provides
– eager processing, i.e. produce a result or side effect
– lazy processing, i.e. creates a stream

• stream
– not a storage of values
i.e. no collection
 view/adaptor of a data source (collection, array, …)


– (mostly) functional
does not alter the underlying data source
produces a result (or side effect)


© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(66)
prototype available of implementation

• e.g. java.lang.Stream<T>
– extended with foreach/filter/map/reduce operations

• design/functionality shown
– based on the current OpenJDK implementation

• might change until Java 8 is final (September 2013)

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(67)
wrap-up

• lambda expressions
– new functional elements for Java
– similarities with anonymous inner classes


advantages: less code, ‘more functional’, faster

• additionally in JSR 335 / JEP 126
– method handles
– extension methods

• JDK changes
– JEP 107: for-each, filter, map, reduce for collections and arrays
– JEP 109: additional smaller changes

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(70)
resources
• Oracle's Java Tutorial: Section on "Lambda Expressions"
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

• JSR 335 "Project Lambda" - The official OpenJDK project page
http://openjdk.java.net/projects/lambda/

• Brian Goetz on "State of the Lambda", 4th edition, December 2011
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html

• Angelika Langer: Lambda/Streams Tutorial & Reference
http://www.angelikalanger.com/Lambdas/Lambdas.html

• Maurizio Cimadamore: Lambda expressions in Java - a compiler
writer's perspective, JAX 2012
http://angelikalanger.com/Conferences/Slides/maurizio_jax_2012.pdf

© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(71)
authors

Angelika Langer
Training & Consulting

Klaus Kreft
Performance Expert, Germany

http://www.AngelikaLanger.com
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(72)
Lambda Expressions

Q&A
© Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved.
http://www.AngelikaLanger.com/
last update: 12/6/2013,10:24

Lambda Expressions in Java

(73)

Más contenido relacionado

La actualidad más candente

Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
Java jdk-update-nov10-sde-v3m
Java jdk-update-nov10-sde-v3mJava jdk-update-nov10-sde-v3m
Java jdk-update-nov10-sde-v3mSteve Elliott
 
Grokking Techtalk #38: Escape Analysis in Go compiler
 Grokking Techtalk #38: Escape Analysis in Go compiler Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking Techtalk #38: Escape Analysis in Go compilerGrokking VN
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSAlberto Paro
 
BCA IPU VB.NET UNIT-I
BCA IPU VB.NET UNIT-IBCA IPU VB.NET UNIT-I
BCA IPU VB.NET UNIT-IVaibhavj1234
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc driversmyrajendra
 
F# and SignalR for a FastWeb
F# and SignalR for a FastWebF# and SignalR for a FastWeb
F# and SignalR for a FastWebRiccardo Terrell
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8Dinesh Pathak
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
Session2 (3)
Session2 (3)Session2 (3)
Session2 (3)DrUjwala1
 

La actualidad más candente (19)

Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
Java jdk-update-nov10-sde-v3m
Java jdk-update-nov10-sde-v3mJava jdk-update-nov10-sde-v3m
Java jdk-update-nov10-sde-v3m
 
Grokking Techtalk #38: Escape Analysis in Go compiler
 Grokking Techtalk #38: Escape Analysis in Go compiler Grokking Techtalk #38: Escape Analysis in Go compiler
Grokking Techtalk #38: Escape Analysis in Go compiler
 
VB.net
VB.netVB.net
VB.net
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
 
BCA IPU VB.NET UNIT-I
BCA IPU VB.NET UNIT-IBCA IPU VB.NET UNIT-I
BCA IPU VB.NET UNIT-I
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
Jdbc
JdbcJdbc
Jdbc
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
F# and SignalR for a FastWeb
F# and SignalR for a FastWebF# and SignalR for a FastWeb
F# and SignalR for a FastWeb
 
Dao example
Dao exampleDao example
Dao example
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Session2 (3)
Session2 (3)Session2 (3)
Session2 (3)
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Jdbc
JdbcJdbc
Jdbc
 
Wwf
WwfWwf
Wwf
 
Api and Fluency
Api and FluencyApi and Fluency
Api and Fluency
 

Destacado

Tuning the HotSpot JVM Garbage Collectors
Tuning the HotSpot JVM Garbage CollectorsTuning the HotSpot JVM Garbage Collectors
Tuning the HotSpot JVM Garbage Collectorslanger4711
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJosé Paumard
 
Garbage Collection Pause Times - Angelika Langer
Garbage Collection Pause Times - Angelika LangerGarbage Collection Pause Times - Angelika Langer
Garbage Collection Pause Times - Angelika LangerJAXLondon_Conference
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 

Destacado (7)

Tuning the HotSpot JVM Garbage Collectors
Tuning the HotSpot JVM Garbage CollectorsTuning the HotSpot JVM Garbage Collectors
Tuning the HotSpot JVM Garbage Collectors
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
 
Garbage Collection Pause Times - Angelika Langer
Garbage Collection Pause Times - Angelika LangerGarbage Collection Pause Times - Angelika Langer
Garbage Collection Pause Times - Angelika Langer
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 

Similar a Jf12 lambdas injava8-1

Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...jaxLondonConference
 
Why scala - executive overview
Why scala - executive overviewWhy scala - executive overview
Why scala - executive overviewRazvan Cojocaru
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Simon Ritter
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & StreamsC4Media
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...Raffi Khatchadourian
 
JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update referencesandeepji_choudhary
 
Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Noopur Gupta
 
Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Derek Ashmore
 
Project Lambda: To Multicore and Beyond
Project Lambda: To Multicore and BeyondProject Lambda: To Multicore and Beyond
Project Lambda: To Multicore and BeyondDmitry Buzdin
 

Similar a Jf12 lambdas injava8-1 (20)

Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
 
Why scala - executive overview
Why scala - executive overviewWhy scala - executive overview
Why scala - executive overview
 
Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
Apouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-futureApouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-future
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
JSR 335 / java 8 - update reference
JSR 335 / java 8 - update referenceJSR 335 / java 8 - update reference
JSR 335 / java 8 - update reference
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013
 
Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30
 
Project Lambda: To Multicore and Beyond
Project Lambda: To Multicore and BeyondProject Lambda: To Multicore and Beyond
Project Lambda: To Multicore and Beyond
 

Último

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 

Último (20)

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 

Jf12 lambdas injava8-1

  • 2. objective • • • • • explain the new language feature of lambda expressions what is the intent? which problem do they solve? what are the syntax elements? how will they be used in the JDK? © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (2)
  • 3. speaker's relationship to topic • independent trainer / consultant / author – – – – – teaching C++ and Java for 15+ years curriculum of a couple of challenging courses co-author of "Effective Java" column author of Java Generics FAQ online JCP member and Java champion since 2005 © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (3)
  • 4. agenda • • • • • • introduction functional interfaces lambda expressions (the details) method references extension methods ‘lambdafication’ of the JDK © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (4)
  • 5. lambda expressions in Java • lambda expressions – aka lambdas; formerly known as closures • concept from functional programming – “anonymous method” / “code-as-data” ‘ad hoc’ implementation of functionality  pass functionality around (parameter, return value)  – similar to (anonymous) inner classes  advantage of lambda expressions: concise syntax + less code “more functional”  © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (5)
  • 6. history • 2006 – 2009 – several proposals for ‘closures in Java’ – no convergence; none fully supported by Sun / Oracle • since 2010 – OpenJDK Project Lambda; tech lead Brian Goetz – JSR 335 (Nov. 2010) "Lambda Expressions for the Java Programming Language" – JEP 126 (Nov. 2011) "Lambda Expressions and Virtual Extension Methods" © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (6)
  • 7. Oracle’s design guideline • aid usage of libraries that … – make use of parallelization on multi core platforms – special focus: JDK • rules out – which features are relevant? – how complex can they be? • general guideline: "as simple as possible" – several (previously discussed) features were dropped – e.g. function types, exception transparency, … © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (7)
  • 8. agenda • • • • • • introduction functional interfaces lambda expressions (the details) method references extension methods ‘lambdafication’ of the JDK © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (8)
  • 9. key goal • support JDK abstractions that … – make use of parallelization on multi core platforms • collections shall have parallel bulk operations – based on fork-join-framework (Java 7) – execute functionality on a collection in parallel i.e. access multiple elements simultaneously  – specified as: JEP 107  details later © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (9)
  • 10. today private static void checkBalance(List<Account> accList) { for (Account a : accList) if (a.balance() < threshold) a.alert(); } • new for-loop style – actually an external iterator object is used: Iterator iter = accList.iterator(); while (iter.hasNext()) { Account a = iter.next(); if (a.balance() < threshold) a.alert(); } • code is inherently serial – traversal logic is fixed – iterate from beginning to end © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (10)
  • 11. Stream.forEach() - definition public interface Stream<T> ... { ... void forEach(Block<? super T> sink); ... } public interface Block<A> { void apply(A a); … } • forEach()’s iteration is not inherently serial – traversal order is defined by forEach()’s implementation – burden of parallelization is put on the library developer  not on the library user © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (11)
  • 12. Stream.forEach() - example Stream<Account> pAccs = accList.parallel(); // with anonymous inner class pAccs.forEach( new Block<Account>() { void apply(Account a) { if (a.balance() < threshold) a.alert(); } } ); // with lambda expression pAccs.forEach( (Account a) -> { if (a.balance() < threshold) a.alert(); } ); • lambda expression – less code (overhead) – only actual functionality  easier to read © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (12)
  • 13. lambda expression a Block<Account> ? Block<Account> block = (Account a) -> { if (a.balance() < threshold) a.alert(); }; • right side: lambda expression • intuitively – ‘something functional’ takes an Account  returns nothing (void)  throws no checked exception  • nothing in terms of the Java type system – just some code / functionality / implementation © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (13)
  • 14. functional interface = target type of a lambda interface Block<A> { public void apply(A a); } Block<Account> pAccs = (Account a) -> { if (a.balance() < threshold) a.alert(); }; • lambdas are converted to functional interfaces – function interface ≈ interface with one method – parameter type(s), return type, checked exception(s) must match – functional interface’s name + method name are irrelevant • conversion requires type inference – lambdas may only appear where target type can be inferred from enclosing context – e.g. variable declaration, assignment, method/constructor arguments, return statements, cast expression, … © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (14)
  • 15. idea behind functional interfaces • interfaces with one method have been the ‘most functional things’ in Java already: interface Runnable interface Callable<T> interface Comparator<T> ... { void run(); } { T call(); }; { boolean compare(T x, T y); } – "as simple as possible" – reuse existing interface types as target types for lambda expressions © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (15)
  • 16. lambda expressions & functional interfaces • functional interfaces interface Block<A> { void apply(A a); } interface MyInterface { void doWithAccount(Account a); } • conversions Block<Account> block = (Account a) -> { if (a.balance() < threshold) a.alert(); }; MyInterface mi = (Account a) -> { if (a.balance() < threshold) a.alert(); }; mi = block; error: types are not compatible • problems error: cannot infer target type Object o1 = (Account a) -> { if (a.balance() < threshold) a.alert(); }; Object o2 = (Block<Account>) (Account a) -> { if (a.balance() < threshold) a.alert(); }; © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (16)
  • 17. evaluation • lambda expression – easy and convenient way to implement ad-hoc functionality • functional interfaces – serve as target types for lambda expressions – integrate lambda expressions into Java type system • advantages – simple: no new elements in Java type system  good for language designers and users – built-in backward compatibility  e.g. can provide a lambda where a Runnable (JDK 1.0) is needed © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (17)
  • 18. evaluation (cont.) • down-side – must define Block<A> to describe parameter type: public void forEach(Block<? super T> sink) ... public interface Block<A> { void apply(A A); } – code overhead, no explicit function type: <T>->void • justification: overhead is acceptable – explicit function types add many more complications – "we (the library providers) do it for you (the library users)" – may be added later  JSR 335 (lambda spec) mentions function types as potential future enhancement © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (18)
  • 19. agenda • • • • • • introduction functional interfaces lambda expressions (the details) method references extension methods ‘lambdafication’ of the JDK © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (19)
  • 20. lambda expression syntax • since September 2011: (Account a) -> { if (a.balance() < threshold) a.alert(); } • previously: # { Account a -> if (a.balance() < threshold) a.alert(); } • syntax: C#, with ‘->’ instead of ‘=>’ – proven concept – quite similar to Scala’s closure syntax, too – ‘->’ instead of ‘=>’ to avoid dueling arrows foo (x => x.size <= 10); © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (20)
  • 21. formal description lambda = ArgList "->" Body ArgList = Identifier | "(" Identifier [ "," Identifier ]* ")" | "(" Type Identifier [ "," Type Identifier ]* ")“ Body = Expression | "{" [ Statement ";" ]+ "}" • options related to – argument list, and – body © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (21)
  • 22. argument list, pt. 1 ArgList = Identifier | "(" Identifier [ "," Identifier ]* ")" | "(" Type Identifier [ "," Type Identifier ]* ")“ a -> { if (a.balance() < threshold) a.alert(); } (a) -> { if (a.balance() < threshold) a.alert(); } (Account a) -> { if (a.balance() < threshold) a.alert(); } • if possible, compiler infers parameter type – inference based on target type, not lambda body • if not possible, parameter type must be specified – parameter type can always be specified • multiple parameters – all parameters either declared or inferred (no mix possible) © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (22)
  • 23. argument list, pt. 2 ArgList = Identifier | ... • omission of parentheses in case of one argument without type identifier possible • examples: a -> { if (a.balance() < threshold) a.alert(); } (int x) -> { return x+1; } x -> { return x+1; } // omit parentheses (int x, int y) -> { return x+y; } (x,y) -> { return x+y; } // can’t omit parentheses // no special nilary syntax () -> { System.out.println(“I am a Runnable”); } © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (23)
  • 24. body Body = Expression | "{" [ Statement ";" ]+ "}" // single statement a -> { if (a.balance() < threshold) a.alert(); } // single expression a -> (a.balance() < threshold) ? a.alert() : a.okay() // list of statements a -> { Account tmp = null; if (a.balance() < threshold) a.alert(); else tmp = a; if (tmp != null) tmp.okay(); } © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (24)
  • 25. return, pt. 1 () -> { return 21; } // returns int (Account a) -> { return a; } // returns Account () // returns long -> { return (long)21; } • return type is always inferred – i.e. cannot be specified explicitly – you might consider to cast the return value © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (25)
  • 26. return, pt. 2 () -> { return 21; } () -> return 21 () -> 21 error !!! • no return with single expression – use of return is an error • return used with list of statements – when using multiple returns: programmer responsible, that the return type can be inferred © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (26)
  • 27. local variable capture int i = 16; Runnable r = () -> { System.out.println(“i is: ” + i); }; • local variable capture – important feature – similar to anonymous inner classes but no explicit final  but still only read access  © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (27)
  • 28. local variable capture (cont.) int i = 16; Runnable r = () -> { System.out.println(“i is: ” + i); }; i++; error because • effectively final variables – same as with anonymous inner classes, but  you do not have to use the final identifier explicitly © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (28)
  • 29. effectively final • local variable capture not much different from inner classes • but caused a lot of discussion – I want write access ! • a look at the details – shows the limitations © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (29)
  • 30. reason for effectively final int i = 0; Runnable r = () -> { for (int j=0; j < 32; j++ ) i = j; }; // start Runnable r in another thread ... error while (i <= 16) /* NOP */; System.out.println(“i is now greater than 16”); • problem: unsynchronized concurrent access • no guaranties from the memory model © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (30)
  • 31. but the effectively final does not prevent … … all evil in the world • consider a mutable object referred to by an effectively final reference int[] ia = new int[1]; Runnable r = () -> { for (int j==; j < 32; j++ ) ia[0] = j); }; // start Runnable r in another thread ... while (ia[0] <= 16) /* NOP */; System.out.println(“ia[0] is now greater than 16”); © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (31)
  • 32. I want write access ! – idioms to come ? File myDir = .... int[] ia = new int[1]; File[] fs = myDir.listFiles( f -> { if (f.isFile() { n = f.getName(); if (n.lastIndexOf(“.exe”) == n.length()-4) ia[0]++; return true; } return false; };); System.out.println("contains " + fs.size + "files, " + ia[0] + "are exe-files"); • no problem, if everything is executed sequentially © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (32)
  • 33. no transparent parallelism ! int[] ia = new int[1]; pAccs.forEach( (Account a) -> { if (a.balance() < threshold) { a.alert(); ia[0]++; } } ); System.out.println(ia[0] + " alerts !!!"); • need to know whether … – methods that take lambda uses multiple threads or not – Stream.forEach() vs. File.list() • currently not expressed in Java syntax – JavaDoc, comment, … © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (33)
  • 34. lambda body lexically scoped, pt. 1 • lambda body scoped in enclosing method • effect on local variables: – capture works as shown before – no shadowing of lexical scope lambda int i = 16; Runnable r = () -> { int i = 0; System.out.println(“i is: ” + i); }; error • different from inner classes – inner class body is a scope of its own inner class final int i = 16; Runnable r = new Runnable() { public void run() { int i = 0; System.out.println(“i is: ” + i); } }; © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 fine Lambda Expressions in Java (34)
  • 35. lambda body lexically scoped, pt. 2 • this refers to the enclosing object, not the lambda – due to lexical scope, unlike with inner classes lambda public class MyClass { private int i=100; } public void foo() { ... Runnable r = () -> {System.out.println(“i is: “ + this.i);}; ... } inner class public class MyClass { private int i=100; public void foo() { ... Runnable r = new Runnable() { private int i=200; public void run() {System.out.println(“i is: “ + this.i);} }; ... } } © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (35)
  • 36. lambdas vs. inner classes - differences • local variable capture: – implicitly final vs. explicitly final • different scoping: – this means different things • verbosity: – concise lambda syntax vs. inner classes' syntax overhead • performance: – lambdas slightly faster (use MethodHandle from JSR 292 ("invokedynamic")) • bottom line: – lambdas better than inner classes for functional types • but what if you add a second method to a functional interface – and turn it into a regular non-functional type ??? © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (37)
  • 37. agenda • • • • • • introduction functional interfaces lambda expressions (the details) method references extension methods ‘lambdafication’ of the JDK © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (38)
  • 38. an example • want to sort a collection of Person objects – using the JDK's new function-style bulk operations and – a method from class Person for the sorting order element type Person class Person { private final String name; private final int age; … public static int compareByName(Person a, Person b) { … } } © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (39)
  • 39. example (cont.) • Stream<T> has a sorted() method Stream<T> sorted(Comparator<? super T> comp) • interface Comparator is a functional interface public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); } inherited from Object • sort a collection/array of Persons Stream<Person> psp = Arrays.parallel(personArray); … psp.sorted((Person a, Person b) -> Person.compareByName(a,b)); © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (40)
  • 40. example (cont.) • used a wrapper that invokes compareByName() psp.sorted((Person a, Person b) -> Person.compareByName(a,b)); • specify compareByName() directly (method reference) psp.sorted(Person::compareByName); – reuse existing implementation – less code • syntax not final, but very likely: “::” © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (41)
  • 41. idea … … behind method references • take an existing method from some class, and make it the implementation of a functional interface – similar to lambda expressions • need context that allows conversion to a target type – similar to lambda expressions • method handles are included in JSR 335 © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (42)
  • 42. agenda • • • • • • introduction functional interfaces lambda expressions (the details) method references extension methods ‘lambdafication’ of the JDK © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (43)
  • 43. problem • no (good) support for interface evolution in Java today • interface evolution = add a new method to an existing interface – problem: all existing implementations of the interface break • concrete situation – extend existing collection interfaces for functional programming – e.g. to interface java.util.Collection<T> add method: void forEach(Block<? super T> block) © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (44)
  • 44. solution • extension method – add a new method to an interface together with a default implementation – implementations of the interface are free to override it, but don’t have to © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (45)
  • 45. example from package java.util: public interface Collection<T> extends … { ... everything as before ... } public void forEach(Block<? super T> block) default { for (T each : this) block.apply(each); } ... • no additional state / no instance fields • implementation based on the functionality of the other methods + the additional parameter(s) from the new method © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (46)
  • 46. notes • extension methods are included in JSR 335 • name: – also know as: defender methods and default methods – in JSR 335 called virtual extension methods  as opposed to C#'s (non-virtual) extension methods (which cannot be overridden) © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (47)
  • 47. extensions methods vs. OO concepts • Java interfaces are not really interfaces anymore • they (can) provide implementation • dilutes the "interface" concept somewhat © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (48)
  • 48. extensions methods vs. OO concepts • Java provides multiple inheritance of functionality now class A extends B implements I, J, K, L {} – A inherits functionality from B – A might inherit functionality from I, J, K, L because these interfaces might provide extensions methods • is it a problem ? - NO ! – relatively safe, no additional state inherited from interfaces © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (49)
  • 49. language evolution C++: • multiple inheritance of functionality – considered dangerous classic Java: • single inheritance of functionality + multiple inheritance only for interfaces – problem: interface evolution => where to provide new functionality ? new languages: • mixins (Ruby) / traits (Scala) – to solve the problem Java 8: • extension methods – fit into existing language – not too different from ‘stateless’ traits in Scala (but without linearization to resolve defaults) © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (50)
  • 50. problem with multiple inheritance the diamond: A B C D • how is A’s state inherited to D ? – once, or – twice (via B and via C) • there is no ‘right’ answer to this question – C++ gives you the option: virtual / non-virtual inheritance – makes it more complicated © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (51)
  • 51. Java 8 the diamond: A B C D • A can only be an interface (not a class) – can have an implementation, but – no state (no instance fields) • no state means no (diamond) problem ! – no issue regarding "how many A parts does D have ?" © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (52)
  • 52. still conflicts – ambiguity #1 • inherit the same method from a class and an interfaces – extends dominates implements – sub-class inherits super-class’s method (not interface’s method) I foo() default { … } C1 C2 foo() { … } inherits foo() from C1 © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (53)
  • 53. ambiguity #2 • inherit the same method from different interfaces – sub-interfaces shadow super-interfaces – if the interfaces are unrelated -> no default at all  I1 results in a compile error foo() default { … } I1 foo() default { … } I2 I2 C foo() default { … } foo() default { … } inherits foo() from I2 © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 C compile-time error ! Lambda Expressions in Java (54)
  • 54. ambiguity #2 (cont.) • can address ambiguity explicitly when implementing class C I1 foo() default { … } I2 foo() default { … } C class C implements I1, I2 { public void foo() { I1.super.foo(); } } – new syntax to qualify the super-interface © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (55)
  • 55. implementation techniques in collection framework • until now: – interfaces for types – skeletal behavior with abstract classes interfaces abstract classes concrete classes Iterable<E> Collection<E> List<E> AbstractCollection<E> AbstractList<E> © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 ArrayList<E> Lambda Expressions in Java (57)
  • 56. beyond interface evolution • interface evolution is primary motivation, but extension methods are useful in themselves • approach: – define interface as always – provide default implementation for those methods that … don’t need state, but  can be based on functionality of other (really abstract) methods  – provide implementation of (really abstract) methods by abstract classes (if functionality can be factored out)  by concrete classes  © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (58)
  • 57. extension methods and retrofits • JDK 1.0 introduced Enumeration • JDK 1.2 replaced it with Iterator • conceivable in Java 8 interface Enumeration<E> extends Iterator<E> { boolean hasMoreElements(); E nextElement(); } boolean hasNext() E next() void remove() throw } default { return hasMoreElements(); } default { return nextElement(); } default { new UnsupportedOperationException(); © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (59)
  • 58. agenda • • • • • • introduction functional interfaces lambda expressions (the details) method references extension methods ‘lambdafication’ of the JDK © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (60)
  • 59. JEP 107: Bulk Data Operations for Collections • JEP = JDK enhancement proposal, for Java 8 • also know as: "for-each/filter/map/reduce for Java" – for-each apply a certain functionality to each element of the collection accountCol.forEach(a -> a.addInterest()); – filter build a new collection that is the result of a filter applied to each element in the original collection Stream<Account> result = accountCol.filter(a -> a.balance() > 1000000 ? true:false); © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (61)
  • 60. JEP 107 (cont.) – map build a new collection, where each element is the result of a mapping from an element of the original collection Stream<Integer> result = accountCol.map(a -> a.balance()); – reduce produce a single result from all elements of the collection accountCol.map(a -> a.balance()) .reduce(new Integer(0), (b1, b2) -> new Integer(b1.intValue()+b2.intValue())); © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (62)
  • 61. JEP 107 (cont.) … additional methods • sorted(), anyMatch(), findFirst(), … – see JavaDoc for yourself © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (63)
  • 62. serial vs. parallel & eager vs. lazy • provides – serial processing, i.e. performed by single thread – parallel processing, i.e. using multiple parallel threads • provides – eager processing, i.e. produce a result or side effect – lazy processing, i.e. creates a stream © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (64)
  • 63. eager vs. lazy - example • consider a sequence of operations – filter with a predicate, map to long value, and apply printing myCol.filter((Account a) -> a.balance() > 1000000) .map((Account a) -> a.balance()) .forEach((long l) -> System.out.format("%dt",l)); • eager – each operation is executed when it is applied • lazy – execute everything after the last operation has been applied – optimize this execution e.g. call a.balance() only once for each account and print it directly without any intermediate collection of balances  © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (65)
  • 64. streams • provides – eager processing, i.e. produce a result or side effect – lazy processing, i.e. creates a stream • stream – not a storage of values i.e. no collection  view/adaptor of a data source (collection, array, …)  – (mostly) functional does not alter the underlying data source produces a result (or side effect)  © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (66)
  • 65. prototype available of implementation • e.g. java.lang.Stream<T> – extended with foreach/filter/map/reduce operations • design/functionality shown – based on the current OpenJDK implementation • might change until Java 8 is final (September 2013) © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (67)
  • 66. wrap-up • lambda expressions – new functional elements for Java – similarities with anonymous inner classes  advantages: less code, ‘more functional’, faster • additionally in JSR 335 / JEP 126 – method handles – extension methods • JDK changes – JEP 107: for-each, filter, map, reduce for collections and arrays – JEP 109: additional smaller changes © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (70)
  • 67. resources • Oracle's Java Tutorial: Section on "Lambda Expressions" http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html • JSR 335 "Project Lambda" - The official OpenJDK project page http://openjdk.java.net/projects/lambda/ • Brian Goetz on "State of the Lambda", 4th edition, December 2011 http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html • Angelika Langer: Lambda/Streams Tutorial & Reference http://www.angelikalanger.com/Lambdas/Lambdas.html • Maurizio Cimadamore: Lambda expressions in Java - a compiler writer's perspective, JAX 2012 http://angelikalanger.com/Conferences/Slides/maurizio_jax_2012.pdf © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (71)
  • 68. authors Angelika Langer Training & Consulting Klaus Kreft Performance Expert, Germany http://www.AngelikaLanger.com © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (72)
  • 69. Lambda Expressions Q&A © Copyright 2003-2012 by Angelika Langer & Klaus Kreft. All Rights Reserved. http://www.AngelikaLanger.com/ last update: 12/6/2013,10:24 Lambda Expressions in Java (73)