4. lambda vs. closure
A lambda is just an anonymous function.
myCollection.filter(e ‑> e.length() >= 5)
A closure is any function which closes over the environment in which it was
defined. This means that it can access variables not in its parameter list.
int minLength = 5;
myCollection.filter(new Predicate(){
boolean apply(MyElement e) {
return e != null ? e.length >= minLength : false;
}
})
11. What do we mean by
closures?
● a unit of deferred execution
● code that can be passed as a value
● can be used in an assignment
statement
● capture of a surrounding environment
12. Lambda Expressions
s -> s.length()
(int x, int y) -> x+y
() -> 42
(x, y, z) -> {
if (x == y) return x;
else {
int result = y;
for (int i = 1; i < z; i++)
result *= i;
return result;
}
}
13. Lambda Syntax
principally because something similar
has been generally well-received in
other Java-like languages (C# and
Scala), and a clearly "better" alternative
did not present itself
17. Lambda
● Effectively final variables
● Shadowing
● break, continue must be local
● this - lambda is not an instance
method. (this == surrounding context
object)
18. Lambda
● Effectively final variables
● Shadowing
● break, continue must be local
● this - lambda is not an instance
method. (this == surrounding context
object)
● throw completes method abruptly
19. Functional Interfaces
A functional interface is an interface
that has just one abstract method, and
thus represents a single function
contract.
20. Functional Interfaces
SAM - Single Abstract Method interfaces
one method excluding Object methods
interface Runnable { void run(); } // Functional
interface Foo { boolean equals(Object obj); }
// Not functional; equals is already an implicit member
interface Comparator<T> {
boolean equals(Object obj);
int compare(T o1, T o2);
}
// Functional; Comparator has one abstract non-Object method
21. Method References
Method reference is a shorthand for a lambda invoking just
that method
System::getProperty
"abc"::length
String::length
super::toString
ArrayList::new
Arrays.sort(ints, Integer::compareTo);
22. Method References
Static methods simply translate like lambda with same
arguments and return type
class Math {
public static int max(int a, int b) {...}
}
interface Operator<T> {
T eval(T left, T right);
}
Operator<Integer> lambda = (a, b) -> Math.max(a, b);
Operator<Integer> methodRef = Math::max;
23. Method References
Non static method reference of type T translates like
lambda with an additional argument of type T
Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase
(s2);
//translates to:
Comparator<String> c = String::compareToIgnoreCase;
24. Method References
Instance method reference translates like lambda with same
arguments and return type (and implicit receiver)
Callable<Integer> l = () -> "boo".length();
//translates to:
Callable<Integer> c = "boo"::length;
26. Compatibility
Cannot add new interface methods
(without forcing current interface users to implement them)
But we need new lambda enabled methods
(on Java core libraries!)
29. Functional Collections
Major changes in collection API:
● Internal iteration support with Iterable/Stream interfaces
(forEach, filter, map, etc)
30. Functional Collections
Major changes in collection API:
● Internal iteration support with Iterable/Stream interfaces
(forEach, filter, map, etc)
● Explicit parallel APIs for greater parallelism support.
These can be combined with Fork/Join to divide the
tasks
31. Functional Collections
Major changes in collection API:
● Internal iteration support with Iterable/Stream interfaces
(forEach, filter, map, etc)
● Explicit parallel APIs for greater parallelism support.
These can be combined with Fork/Join to divide the
tasks
● Greater stress on immutability and avoiding in-place
mutation which was done in the conventional for-each
loops
34. Streams
● No storage - nothing is stored in stream
● Functional in nature - new values are produced
35. Streams
● No storage - nothing is stored in stream
● Functional in nature - new values are produced
● Laziness-seeking. Many operations can be
implemented lazily
36. Streams
● No storage - nothing is stored in stream
● Functional in nature - new values are produced
● Laziness-seeking. Many operations can be
implemented lazily
● Bounds optional. Think of infinite stream
38. Parallelism
//sequential
int sum = myCollection.stream()
.filter(b -> b.getColor() == BLUE)
.map(b -> b.getWeight())
.sum();
//parallel
int sum = myCollection.parallel()
.filter(b -> b.getColor() == BLUE)
.map(b -> b.getWeight())
.sum();
39. Advantages
● Elements may be computed lazily. If we apply a Mapper
to a collection of a thousand elements but only iterate
over the first three, the remaining elements will never be
mapped.
40. Advantages
● Elements may be computed lazily. If we apply a Mapper
to a collection of a thousand elements but only iterate
over the first three, the remaining elements will never be
mapped.
● Method chaining is encouraged. Hence there's no need
to store intermediate results in their own collections.
41. Advantages
● Elements may be computed lazily. If we apply a Mapper
to a collection of a thousand elements but only iterate
over the first three, the remaining elements will never be
mapped.
● Method chaining is encouraged. Hence there's no need
to store intermediate results in their own collections.
● Internal iteration hides implementation decisions. For
example, we could parallelize a map() operation just by
writing myCollection.parallel().map(e ‑> e.length()).
42. Try it out today!
The prototype compiler is being implemented in OpenJDK.
● Source code is available at http://hg.openjdk.java.
net/lambda/lambda
● Binary snapshots of the lambda-enabled JDK prototype
are available athttp://jdk8.java.net/lambda
IDE support:
● Netbeans 8 Nightly Builds with experimental Lambda
support
● IDEA 12 EAP with experimental Lambda support
47. Oldies: Date
● Mutable
● Years being indexed from 1900
● Months being indexed from 0
Ex.:
Date d = new Date(1L);
System.out.println(d.toString());
48. Oldies: Date
● Mutable
● Years being indexed from 1900
● Months being indexed from 0
Ex.:
Date d = new Date(1L);
System.out.println(d.toString());
//Thu Jan 01 02:00:00 EET 1970
51. Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
methods)
● Very difficult to extend (add new calendars)
52. Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
methods)
● Very difficult to extend (add new calendars)
Ex.:
Calendar c = Calendar.getInstance();
int weekday = c.get(DAY_OF_WEEK);
53. Oldies: Calendar
● Mutable
● Not very convenient (lack of simple field
methods)
● Very difficult to extend (add new calendars)
Ex.:
Calendar c = Calendar.getInstance();
int weekday = c.get(DAY_OF_WEEK);
Date d = c.getTime();
56. JSR 310
● Immutable
● Defines consistent language for domain
○ Offset from UTC vs TimeZone
○ Machine vs Human
○ ISO 8601
57. JSR 310
● Immutable
● Defines consistent language for domain
○ Offset from UTC vs TimeZone
○ Machine vs Human
○ ISO 8601
● No old Date/Calendar usage (clean)
58. JSR 310
● Immutable
● Defines consistent language for domain
○ Offset from UTC vs TimeZone
○ Machine vs Human
○ ISO 8601
● No old Date/Calendar usage (clean)
● Extensible
59. JSR 310
● Immutable
● Defines consistent language for domain
○ Offset from UTC vs TimeZone
○ Machine vs Human
○ ISO 8601
● No old Date/Calendar usage (clean)
● Extensible
● Led by JodaTime creator (S. Colebourne)
71. Type Annotations
● In Java 7 we have annotations on
declarations
Ex.:
class SomeClass { … }
class ListElement<E> { … }
public void v() (int I) {
long l;
{
72. Type Annotations
● JSR-308 brings annotations on Type use
● Are an enabler for the checkers framework
Ex.:
new @Interned MyObject();
myString = (@NonNull String) myObject;
void monitorTemperature() throws
@Critical TemperatureException { ... }
73. Repeating Annotations
● Before
@Schedules ({
@Schedule(dayOfMonth="Last"),
@Schedule(dayOfWeek="Fri", hour="23")
({
public void doPeriodicCleanup() { ... }
74. Repeating Annotations
● Before
@Schedules ({
@Schedule(dayOfMonth="Last"),
@Schedule(dayOfWeek="Fri", hour="23")
({
public void doPeriodicCleanup() { ... }
● After
@Schedule(dayOfMonth="Last”)
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }