13 Java 8 Lambda Expressions Part 1
13 Java 8 Lambda Expressions Part 1
Lambda Expressions
in Java 8:
Part 1 – Basics
Originals of slides and source code for examples: http://courses.coreservlets.com/Course-Materials/java.html
Also see Java 8 tutorial: http://www.coreservlets.com/java-8-tutorial/ and many other Java EE tutorials: http://www.coreservlets.com/
Customized Java training courses (onsite or at public venues): http://courses.coreservlets.com/java-training.html
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic. λ
Motivation and
Overview
Slides © 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Many Languages Let You Pass Functions Around
• Dynamically (and usually weakly) typed
– JavaScript, Lisp, Scheme, etc.
• Strongly typed
– Ruby, Scala, Clojure, ML, etc.
• Functional approach proven concise, flexible, and parallelizable
– JavaScript sorting
var testStrings = ["one", "two", "three", "four"];
testStrings.sort(function(s1, s2) {
return(s1.length - s2.length);});
testStrings.sort(function(s1, s2) {
return(s1.charCodeAt(s1.length - 1) –
s2.charCodeAt(s2.length - 1));});
7
Surface Advantage of Lambdas:
Concise and Expressive
• Old
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doSomethingWith(e);
}
});
• New
button.addActionListener(e -> doSomethingWith(e));
“Vigorous writing is concise... This requires not that the writer make all sentences short, or avoid all details
8 and treat subjects only in outline, but that every word should tell.” – Strunk and White, The Elements of Style.
Underlying Advantages:
Support New Way of Thinking
• Encourage functional programming
– When functional programming approach is used, many classes of problems are
easier to solve and result in code that is clearer to read and simpler to maintain
• Functional programming does not replace object-oriented programming in Java 8.
OOP is still the main approach for representing types. But functional programming
augments and improves many methods and algorithms.
• Support streams
– Streams are wrappers around data sources (arrays, collections, etc.) that use
lambdas, support map/filter/reduce, use lazy evaluation, and can be made parallel
automatically.
• Cannot be made parallel automatically
for(Employee e: employees) { e.giveRaise(1.15); }
• Will automatically be run in parallel
employees.stream().parallel().forEach(e -> e.giveRaise(1.15));
9
coreservlets.com – custom onsite training
Lambdas:
Syntax
Slides © 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Main Points
• You write what looks like a function
– Arrays.sort(testStrings, (s1, s2) -> s1.length() - s2.length());
– taskList.execute(() -> downloadSomeFile());
– someButton.addActionListener(event -> handleButtonClick());
– double d = MathUtils.integrate(x -> x*x, 0, 100, 1000);
• You get an instance of a class that implements the interface
that was expected in that place
– The expected type must be an interface that has exactly one (abstract) method
• Called “Functional Interface” or “Single Abstract Method (SAM) Interface”
– The designation of a single ABSTRACT method is not redundant, because in Java 8 interfaces can
have concrete methods, called “default methods”. Java 8 interfaces can also have static methods.
11
Example: Sorting Strings by Length
• Java 7 example
Arrays.sort(testStrings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return(s1.length() - s2.length());
}
});
• Java 8 alternative
Arrays.sort(testStrings, (s1, s2) -> s1.length() - s2.length());
The above is simply by replacing the anonymous inner class with a lambda, and no new capabilities are needed other than lambdas. But, Java 8 also added several sorting-related methods, one of which is Comparator.comparing.
So, the above could also be: Arrays.sort(testStrings, Comparator.comparing(String::length));
Method references like String::length are discussed in the next lambda section. Comparator.comparing and similar methods are discussed in section on lambdas and higher-order functions.
12
15
Optional Step 4 –
Omit Parens When there is Exactly One Param
• Idea
– If the method of the interface has exactly one parameter, the parens are optional
• Java 7
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doSomethingWith(e);
}
});
• Java 8 with parens
button.addActionListener((e) -> doSomethingWith(e));
• Java 8 without parens
button.addActionListener(e -> doSomethingWith(e));
16
Thinking About
Lambdas
Slides © 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
• Function types
– Java 8 does not technically have function types, since under the hood, lambdas
become instances of classes that implement whatever interface was expected.
21 Nevertheless, you normally think of lambdas as functions.
Where Can Lambdas Be Used?
• Find any variable or parameter that expects an interface that
has one method
• Technically 1 abstract method, but in Java 7 there was no distinction between a 1-
method interface and a 1-abstract-method interface. These 1-method interfaces are
called “functional interfaces” or “SAM (Single Abstract Method) interfaces”.
– public interface Blah { String foo(String someString); }
• Code that uses interface is the same
– public void someMethod(Blah b) { … b.foo(…) …}
• Code that uses the interface must still know the real method name in the interface
• Code that calls the method that expects the interface can
supply lambda
– someMethod(s -> s.toUpperCase() + "!");
22
Example:
Numerical
Integration
Slides © 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Example: Numerical Integration
• Goals
– Simple numerical integration using rectangle (mid-point) rule
Diagram from
http://en.wikipedia.org/wiki/Numerical_integration
– Want to use lambdas to make it convenient and succinct to supply the function that
will be intetgrated
• Need to define a functional (SAM) interface with a “double eval(double x)” method to
specify function to be integrated
24
Interface
26
27
Testing Results
MathUtilities.integrationTest(x -> x*x, 10, 100);
MathUtilities.integrationTest(x -> Math.pow(x,3), 50, 500);
MathUtilities.integrationTest(x -> Math.sin(x), 0, Math.PI);
MathUtilities.integrationTest(x -> Math.exp(x), 2, 20);
Output
Estimating integral of x^2 from 10.000 to 100.000.
Exact answer = 100^3/3 - 10^3/3.
~= 333,000.00000000
For numSlices = 10 result = 332,392.50000000
For numSlices = 100 result = 332,993.92500000
For numSlices = 1,000 result = 332,999.93925000
For numSlices = 10,000 result = 332,999.99939250
For numSlices = 100,000 result = 332,999.99999393
For numSlices = 1,000,000 result = 332,999.99999994
29
coreservlets.com – custom onsite training
Making a Reusable
Timing Utility
Slides © 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Timing
• Goals
– Pass in a “function”
– Run the function
– Print elapsed time
• Problem: Java evaluates args on the call
– TimingUtils.timeOp(someSlowCalculation());
• The calculation is computed before timeOp is called!
• Solution: use lambdas
– TimingUtils.timeOp(() -> someSlowCalculation());
• timeOp can run the calculation internally
• Could be done with inner classes
– And in fact we did so in fork-join section
– But, code that called timeOp was long, cumbersome, and obtuse
31
The Op Interface
public interface Op {
void runOp();
}
33
Main Testing Code
public class TimingTests {
public static void main(String[] args) {
for(int i=3; i<8; i++) {
int size = (int)Math.pow(10, i);
System.out.printf("Sorting array of length %,d.%n", size);
TimingUtils.timeOp(() -> sortArray(size));
}
}
Output
Sorting array of length 1,000.
Elapsed time: 0.002 seconds.
Sorting array of length 10,000.
Elapsed time: 0.004 seconds.
Sorting array of length 100,000.
Elapsed time: 0.020 seconds.
Sorting array of length 1,000,000.
Elapsed time: 0.148 seconds.
Sorting array of length 10,000,000.
Elapsed time: 1.339 seconds.
34
35
coreservlets.com – custom onsite training
Final Lambda
Examples
Slides © 2016 Marty Hall, [email protected]
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Arrays.sort(testStrings,
(s1, s2) -> s1.length() - s2.length());
taskList.execute(() -> downloadSomeFile());
button.addActionListener(event -> handleButtonClick());
double d = MathUtils.integrate(x -> x*x, 0, 100, 1000);
37
A Few More Samples (Continued)
• As variables (makes real type more obvious)
AutoCloseable c = () -> cleanupForTryWithResources();
Thread.UncaughtExceptionHandler handler =
(thread, exception) -> doSomethingAboutException();
Formattable f =
(formatter, flags, width, precision) -> makeFormattedString();
ContentHandlerFactory fact =
mimeType -> createContentHandlerForMimeType();
CookiePolicy policy =
(uri, cookie) -> decideIfCookieShouldBeAccepted();
Flushable toilet = () -> writeBufferedOutputToStream();
TextListener t = event -> respondToChangeInTextValue();
38
Wrap-Up
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.
Summary: Big Ideas
• Yay! We have lambdas
– Concise and succinct
– Retrofits into existing APIs
– Familiar to developers that know
functional programming
– Fits well with new streams API
– Also have method references and prebuilt functional interfaces
• Boo! We do not have full functional programming (?)
– Type of a lambda is class that implements
interface, not a “real” function
• Must create or find interface first,
must know method name
– Cannot use mutable local variables
40
Summary: Syntax
• Replace this use of an anonymous inner class
doSomething(new SomeOneMethodInterface() {
@Override
public SomeType methodOfInterface(args) {
return(value);
}
});
• With this use of a lambda
doSomething((args) -> value);
• And, if method has exactly one parameter, you can omit parens around the args
• Defining a one-method interface to use with lambdas
– Interface itself is almost the same as Java 7 (except for annotation we will see later)
– Code that uses the interface is exactly the same as in Java 7
41 – Code that calls method that expects the interface type can now use lambda
coreservlets.com – custom onsite training
Questions?
More info:
http://courses.coreservlets.com/Course-Materials/java.html – General Java programming tutorial
http://www.coreservlets.com/java-8-tutorial/ – Java 8 tutorial
http://courses.coreservlets.com/java-training.html – Customized Java training courses, at public venues or onsite at your organization
http://coreservlets.com/ – JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training
Many additional free tutorials at coreservlets.com (JSF, Android, Ajax, Hadoop, and lots more)
For additional materials, please see http://www.coreservlets.com/. The Java tutorial section contains
complete source code for all examples in this tutorial series, plus exercises and exercise solutions for each topic.