3. Topics Covered
• Lambda Support
• Lambda syntax
• Interface enhancements
• Convert inner class to
Lambda
• forEach & Streams
• Method & Constructor
References
• Functional API
4. Download Links & IDE Support
• Regular JDK download link
• http://jdk8.java.net/download.html (for EAs)
• Netbeans
• IntelliJ
• Eclipse
5. Maven Support
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <!-- or higher – up to 3.1 now -->
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
6.
7.
8. Lambdas
A lambda expression is like a method: it provides
a list of formal parameters and a body—an
expression or block—expressed in terms of
those parameters.
Expressions:
s -> s.length()
(int x, int y) -> x+y
() -> 42
Assign lambda to functional interface:
Runnable r1 = () ->
System.out.println("My Runnable");
9.
10. Lambdas
Blocks:
(x, y, z) -> {
if (x==y) return x;
else {
int result = y;
for (int i = 1; i < z; i++)
result *= i;
return result;
}}
11. Typical Use Cases
• Anonymous classes (GUI listeners)
• Runnables / Callables
• Comparator
• Apply operation to a collection via foreach
method
• Chain operations on a collection with Stream API
12.
13.
14. MOAR !!!
Monday
• Programming with Lambda
Expressions in Java [CON1770]
11 AM Hilton Imperial A
• GS Collections and Java 8:
Functional, Fluent, Friendly, and
Fun [CON5423]
11 AM Hilton Imperial B
• Under the Hood of Java 8 Parallel
Streams with an Oracle Solaris
Dtrace [BOF1937]
9: 45 PM Moscone North 131
Tuesday
• Jump-Starting Lambda
[TUT3371]
10:30 AM Hilton Yosimite B/C
• Lambda Under the
Hood [CON4180]
11 AM Hilton Imperial A
• Lambda Q&A Panel [CON3374]
1:30 PM Hilton Yosimite B/C
17. Effectively Final
• For both lambda bodies and inner classes, local
variables in the enclosing context can only be
referenced if they are final or effectively final.
• A variable is effectively final if its value is not
reassigned after its initialization.
• No longer need to litter code with final keyword
18.
19. Interface Defender Methods
• Interface methods with bodies
• default keyword
• More graceful API evolution
• Interfaces have no state
• Static methods not inherited
• Can reference abstract method
• Called “Extended Interfaces” if no abstract methods
present
20.
21. Super!
• Extended Interfaces can
extend other extended
interfaces
• Methods can be
overridden
• Can decorate parent
definitions via super
interface I1 { default void
method1() {//do stuff}}
interface I2 extends I1{
default void method1() {
super.method1();
//do new stuff
}}
25. Convert Anonymous Class to Lambda
from http://learnjavafx.typepad.com/weblog/2013/02/mary-had-a-little-%CE%BB.html
// Anonymous inner class for event handling
.onAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
anim.playFromStart();
}
})
26.
27. Convert Anonymous Class to Lambda
• .onAction((ActionEvent) -> {
anim.playFromStart(); } })
• .onAction((e) -> {anim.playFromStart();})
33. forEach
• forEach() - available on Iterator & Map interfaces and their
implementations
• Allows for internal control of iteration of elements for
possible parallel operation
List<String> names =
Arrays.asList(“Bill", “Ed", “Al");
names.forEach(e -> { System.out.println(e); });
But be careful!!!
34.
35.
36.
37. MOAR!!!
• GS Collections and Java 8: Functional, Fluent,
Friendly, and Fun [CON5423]
Monday 11 AM Hilton Imperial B
• Autumn Collections: From Iterable to Lambdas,
Streams, and Collectors [TUT3472]
Tuesday 8:30 AM Hilton Yosemite A
• New Tricks for Old Dogs: Collections in Java 8
[CON6309] Thursday 4 PM Hilton Imperial A
38.
39. java.util.stream
• Classes to support functional-style operations
on streams of values
• Stream<T> - A sequence of elements
supporting sequential and parallel bulk ops
41. java.util.stream
• All other interfaces in stream package
accessible through Stream interface
• Collector<T,R> - A (possibly parallel) reduction
operation.
• FlatMapper<T,U> - Maps element of type T to
zero or more elements of type U.
42.
43.
44. MOAR!!!
• Journey’s End: Collection and Reduction in the
Stream API [TUT3836]
Monday 8:30 AM Hilton Yosemite A
• Programming with Streams in Java 8 [CON1771]
Monday 4 PM Hilton Imperial A
• Parallel Streams Workshop [CON3372]
Wednesday 10 AM Hilton Yosemite A
• Loads more!!!
45.
46. java.util
• Spliterator<T> provides traversal operations
• Optional<T>
– Returned by Stream’s aggregate methods
find*(), reduce(), min(), max()
– Call get() to get the value it’s holding
47.
48. Method & Constructor References
• A method reference is used to refer to a (static
or instance) method without invoking it
• A constructor reference is similarly used to
refer to a constructor without creating a new
instance of the named class or array type.
• Specified with the :: (double colon) operator
49. Method & Constructor References
• Provide a way to refer to a method / constructor without
invoking it
• Examples:
System::getProperty
"abc"::length
String::length
super::toString
ArrayList::new
int[]::new
50.
51. Convert call to Method Reference
public class Test {
static void foo(){}
static {
new Runnable() {
@Override
public void run() {
Test.foo();
}
}.run();
}}
52. Convert call to Method Reference
public class Test {
static void foo(){}
static {
((Runnable) () -> Test.foo()).run();
}
}
53. Convert call to Method Reference
public class Test {
static void foo(){}
static {
((Runnable) Test::foo()).run();
}
}
54.
55. Use a Method Reference
This
bttnExit.setOnAction(
(actionEvent) -> {
try {
stop();
} catch (Exception e) {
// TODO: add error handling
} });
Can be
bttnExit.setOnAction(
this::onExitButtonClick);
...
void onExitButtonClick() {
try {
stop();
} catch (Exception e) {
// TODO: add error handling
}
}
56. Use a Constructor Reference
interface Factory<T> { T make(); }
Factory<List<String>> f1 =
ArrayList::<String>new;
• Every time make() is invoked, it will return a
new ArrayList<String>
59. Whatever!
Method assigned to privileged interface:
public class Main {
public static class NotAutoCloseable {
public void close() throws Exception {
System.out.println("CLOSE"); } }
public static void main(String... args) throws Exception {
NotAutoCloseable nac = new NotAutoCloseable();
try (AutoCloseable ac = nac::close) {}}}
60.
61.
62. Functional Interface
• Has just one abstract
method. (Can have other
methods with bodies)
• Represents a functional
contract.
• The @FunctionalInterface
annotation helps ensure the
Functional Interface
contract is honored
63. Functional Interface
• What happens when you have more than one
abstract method & use @FunctionalInterface?
64.
65.
66. java.util.function
• Functional interfaces provide target types for lambda
expressions and method references
• Consumer<T>
• Function<T,R>
• Supplier<T>
• Predicate<T>
• Unary/BinaryOperator<T>
• Bi(Consumer/Function/Predicate)<T,U(,R)>
67.
68. public static <X, Y> void processElements(
Iterable<X> source, Predicate<X> tester,
Function <X, Y> mapper, Consumer<Y> block) {
for (X p : source) {
if (tester.test(p)) {
Y data = mapper.apply(p);
block.accept(data);
} } }
from http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
69.
70. MOAR!!!
• Thinking in Functional Style [CON1767]
Monday 2:30 PM Hilton Yosemite B/C
• Twins: FP and OOP [CON2159]
Monday 2:30 PM Hilton Continental 7/8/9
• Loads more (insanely huge list for functional
programming)
71.
72. New Java 8 Feature Overview
• http://openjdk.java.net/projects/jdk8/features
• http://java.dzone.com/articles/java-%E2%80%93-
far-sight-look-jdk-8
Java 8 Maven Support
• http://illegalargumentexception.blogspot.com/20
12/08/java-lambda-support-in-java-8.html
5 minute version at the Ignite Talk – Tuesday 7 – 9 PM Hilton Imperial A
15% discount on the next J1 conference if you go to 16 or more sessions
Don’t get too creative with blocks, or you’ll defeat the purpose of lambdas. We’ll explore alternative solutions later using method references.
When you see a slide that says MOAR! I want you to yell MOAR!!!
Let’s try this!!!
(Go back one slide and flip to this slide again)
Test soon!!!
Effectively final allows you to read code faster
We wrote all this code in red, when all we really wanted to do was have an animation play
Bullet point 1 - The lambda type is inferred by the compiler as EventHandler<ActionEvent> because the onAction() method takes an object of type EventHandler<ActionEvent>.
Bullet point 2 - The parameter in this lambda expression must be an ActionEvent, because that is the type specified by the handle() method of the EventHandler interface.
Bullet point 3 - When a lambda expression has a single parameter and its type is inferred, the parentheses are not required
Bullet point 4 - Because the block of code in our lambda expression contains only one statement, we can simplify it even further by removing the curly braces
Trivia: Who knows who Bill, Ed and Al are?
If you don’t know, I’ll tell you later…
Bill, Ed and Al are Bill Coleman, Ed Scott, and Alfred Chuang, the founders of… BEA!!!
Collector<T,R> - A (possibly parallel) reduction operation that folds input elements into a mutable result container.
FlatMapper<T,U> - An operation that maps an element of type T to zero or more elements of type U.
Uh, sorry kid, not quite the streams we were talking about…
Spliterator<T> - A provider of element traversal operations for a possibly-parallel computation.
Optional<T> - A container object which may or may not contain a non-null value, key enabler of functional programming
A method reference is used to refer to a (static or instance) method without invoking it
A constructor reference is similarly used to refer to a constructor without creating a new instance of the named class or array type.
A static method (ClassName::methName)
An instance method of a particular object (instanceRef::methName)
A super method of a particular object (super::methName)
An instance method of an arbitrary object of a particular type (ClassName::methName)
A class constructor reference (ClassName::new)
An array constructor reference (TypeName[]::new)
Lambda blocks can be avoided by using method references, and you get a method out of it
Ouch!
Poor Bad Luck Brian…
Really, trying to write Java in a functional style before lambdas looked hideous
Consumer<T> - Action to be performed on an object.
Function<T,R> - transform a type T to a return type R.
Supplier<T> - A supplier of objects (e.g. factory).
Predicate<T> - Determines if the input object matches some criteria.
Unary/BinaryOperator<T> - An operation upon a single / two operand(s) yielding a result.
Bi(Consumer/Function/Predicate)<T,U(,R)> - Accepts two input arguments, yields result (R) if specified