SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Lambda Expressions pt1
1.1 Getting Started with Java 8
1.2 Java 8 References
1.3 Quick review of Pre-Lambda Handlers
1.4. Functional Interface Annotation
1.5 Lambda Handlers
1.6 Why Java 8?
1.7 Wra-Up
Lars A. Lemos
1
1.Getting Started,Setup and
Review
1.1 Getting Started with Java 8
1.2 Java 8 References
1.3 Quick review of Pre-Lambda Handlers
1.4. Functional Interface Annotation
1.5 Lambda Handlers
1.6 Why Java 8?
1.7 Wra-Up
Lars A. Lemos
2
Starting point
 Jdk 8 download, Jdk 8 Demos and Samples
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-
downloads-2133151.html
 More Info
http://docs.oracle.com/javase/8/docs/
http://docs.oracle.com/javase/tutorial/java/javaOO/lambda
expressions.html
 IDE
• IntelliJ IDEA 13 - : http://www.jetbrains.com/idea/download/
• Netbeans 8 : https://netbeans.org/downloads/
• Eclipse Kepler : https://www.eclipse.org/downloads/
Lars A. Lemos 3
1.1 Getting Started with Java 8
 Books
Functional Programming in Java - Venkat Subramanian
Java 8 Lambdas: Pragmatic Functional Programming – Richard Warburton
Java SE 8 for the Really Impatient – Cay S. Horstman
Java The Complete Reference 9th Ed – Herbert Schildt
Lars A. Lemos 4
1.2 Java 8 References
1.3 Quick review of Pre-Lambda Handlers
 Anonymous inner classess
 Idea
You need code to respond a button click, to run in the background
for threads, or to handle sorting comparisons.
 Pre-lambda alternatives
 Separete class
• Arrays.sort(theArray, new SeparateClass(...));
 Main class(which implements interface)
• Arrays.sort(theArray, this);
 Named inner class
• Arrays.sort(theArray, new InnerClass(...));
 Anonymous inner class
• Arrays.sort(theArray, new
Comparator<String>(){...});
Lars A. Lemos 5
1.3 Quick review of Pre-Lambda Handlers
 Separete class
public class StringSorter1 {
public void doTests() {
String[] testStrings = {"one","two","three","four"};
System.out.println("Original: ");
ArrayUtils.printArray(testStrings);
Arrays.sort(testStrings, new StringLengthComparator());
System.out.println("After sorting by length: ");
ArrayUtils.printArray(testStrings);
Arrays.sort(testStrings, new LastLetterComparator());
System.out.println("After sorting by last letter: ");
ArrayUtils.printArray(testStrings);
}}
Example: StringSorter1.java
 Advantages
• Flexible: can pass arguments to class constructor
• More reusable: loosely coupled
 Disadavantages
• Need extra stpes to call method in main app. How does handler call method in main
app?
• It needs reference to the main app to do so.
Lars A. Lemos 6
1.3 Quick review of Pre-Lambda Handlers
 Implementing Interface
 Advantages
• No extra steps need to call methods in the main app.
o The code is part of the main app, so it can call any
method or access any instance variable, even private
ones.
• Simple
o Widely used in real life for button handlers, when you
know you will have only one button, or for threading
code, when you need one method to run in the
background.
 Disadavantages
• Inflexible: hard to have multiple different versions, since
you cannot pass argumens to the handler.
o For example, if you want to sort array using two or more
ways? If you pass “this” to the second argument in
Arrays.sort, it will refer to the same “compare” method both
times. Lars A. Lemos 7
1.3 Quick review of Pre-Lambda Handlers
 Named Inner Class
 Advantages
• No extra steps need to call methods in the main app.Inner class have
full access to all methods and instances variables of surrounding class,
including private ones.
o However if there is a name conflict, it is necessary to use the
unpopular OuterClass.this.name syntax.
• Flexible: can define constructor and pass arguments.
 Disadavantages
o A bit harder to understand.
 Anonymous Inner Class
 Advantages
• Full access to code of surrounding class (even private methods and
variables).
• Slightly more concice than named inner class(but still bulk and
verbose).
 Disadavantages
o Harder to understand
o Not reusable(cannot use the anonymous class definition in more).
Example: StringSorter3.java Lars A. Lemos 8
1.4 @FunctionalInterface Annotation
 @FunctionalInterface
 Tells the compiler you intend this to be a functional Single Abstract Method (SAM)
interface
 One with exactly one abstract method
 Thus, for which lambdas can be used.
 Check performed at compile time
 Also informs others developers that lambdas can be used for this interface
 Analogous to @Override
 Does extra work at compile time, but no difference at run time (assuming it passes
the check)
 Goals
 Simple numerical integration using rectangle (mid-point) rule
 Use lambdas for function to be integrated. Convenient and succinct.
Example: SimpleInterface.java , TestInterface.java
Lars A. Lemos 9
1.3 Lambda Handlers
 Desired features
 Full access to code from surrounding class
 No confusion about meaning of “this”
 Much more concise, succinct, and readable
 Enourage a functional programming style
 Lambda
Arrays.sort(testStrings, (s1, s2) -> s1.length() –
s2.length());
 What is the under the hood implementation
Arrays.sort(testStrings, new Comparator<String>() {
@Override
public int compare(string s1, String s2) {
s1.length() – s2.length());
}
});
Lars A. Lemos 10
1.4 Why Java 8 and Lambdas ?
 Weakly (and usually dynamically ) typed
 JavaScript, Lisp, Scheme, etc.
 Strongly typed
 Ruby, Scala, Clojure, etc.
 Functional approach proven concise, useful, and
parallelizable
 Concise syntax(clear than anonymous inner classes)
 Convienent for new streams library
 Shapes.forEach(s -> s.setColor(Color.RED));
 Similar constructs used in other languages
 Callbacks, closures, map/reduce idiom
 Step toward true functional programming
 When funct. Prog approach is used, many classes of problems
are easier to solve and result in code that is clearer to read and
simpler to maintain. Lars A. Lemos 11
2. Lambdas Basics
2.1 Lambdas Expressions
2.2 Type Inferencing
2.3 Implied Return Values
2.4 Omitting Parents for One-Arg Lambdas
2.5 Effectively Final Local Variables
2.6 @FunctionalInterface Annotation
2.7 Method References
2.8 The java.util.function Package
2.9 Wrap Up
Lars A. Lemos
12
2.1 Lambada Expressions
 Replace this
new SometInterface () {
@Override
public someType someMethod(args) { body; }
}
 With this
(args) - > { body }
 Example
Array.sort(testStrings, new Comparator<String> () ) {
@Override
public int compare(String s1, String s2) {
return (s1.length() – s2.length());
}
Array.sort(testStrings,
(String s1, String s2) - > {
return (s1.length() – s2.length() ) ; } ) ;
Example: JavaLambdas.java
Lars A. Lemos 13
2.1 Lambada Expressions Part
1Basics
 Old
button.addActionListener (new ActionListener () {
@Override
public void actionPerformed(ActionEvent event) {
action();
}
});
 New
button.addActionListener(event -> action());
 You get an Instance of an inner class that
implements interface
 The expected type must be an interface that has exactly one
(abstract).
 It’s called “Functional Interface” or “Single Abstract Method” (SAM)
Example: ButtonFrame1.java
Lars A. Lemos 14
2.2 Type Inferencing
 Types in argument list can usually be omitted
 Since Java usually already knows the expected parameter types
for the single method of the functional interface (SAM interface)
 Basic lambda
(Type1 var1, Type2 var 2 …) - > { method body }
 Lambda with type inference
( var1, var 2 …) - > { method body }
Lars A. Lemos 15
2.2 Type Inferencing
 Replace this
new SometInterface () {
@Override
public someType someMethod( T1 v1, T2 v2 ) { body; }
}
 With this
(v1, v2) - > { body }
Array.sort(testStrings, new Comparator<String> () ) {
@Override
public int compare(String s1, String s2) {
return (s1.length() – s2.length());
}
Array.sort(testStrings,
(s1, s2) - > {
return (s1.length() – s2.length() ) ; } ) ;
Example: JavaLambdas.java
Lars A. Lemos 16
2.3 Implied Return Values
 For body, use expression instead of block
 Value of expression will be the return value, with no explicit “return” needed
 If method has a void return type, then automatically no return value
 Since lambdas are usually used only when method body is short, this
approach (using expression instead of block ) is very common.
 Previous Version
(var1, var2) - > { return (something); }
 Lambda with expression for body
(var1, var2) - > { something }
Example: JavaLambdas.java
Lars A. Lemos 17
2.4 Omitting Parents for One-Arg
Lambdas
 If method take single argument, parents
optional
 No type should be used: you must let Java infer the type.
 Ommiting types is normal practice
 Previous Version
( varName ) - > someResult()
 Lambda with parentheses omitted
var - > someResult()
Example: ButtonFrame3.java
Lars A. Lemos 18
2.5 Effectively Final Local Variables
 Lambdas can refer to local variables that are not
declared final (but are never modified)
 This is known as “effectively final” – variables where it would have been legal
to declare them final.
 You can still refer to mutable instance variables.
 “this” in a lambda refers to main class, not inner class that was created for
the lambda. There is no OuterClass.this. Also, no new level of scoping.
 With explicit declaration
final String s = “…”;
doSomething(someArg - > use(s) );
 Effectively final
String s = “…”;
doSomething(someArg - > use(s) );
Example: ButtonFrame4.java
Lars A. Lemos 19
2.6 @FunctionalInterface Annotation
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);
Example: MathUtilities.java
Lars A. Lemos 20
2.7 Method References
 Use ClassName:: staticMethodName or
variable::instanceMethodName for lambdas
 Ex: Math::cos or myVar::myMethod
 The function must match signature of method in functional (SAM)
interface to which it is assigned.
 The type is found only from the context
 The type of a method reference depends on what it is assigned to.
This is always true with lambdas, but more obvious here.
 Ex: no predifined type for Math::cos
Lars A. Lemos 21
2.7 Method References
 In previous example, replace
MathUtilities.integrationTest(x-> Math.sin(x), 0, Math.PI );
MathUtilities.integrationTest(x-> Math.exp(x), 2, 20 );
 With these
MathUtilities.integrationTest( Math::sin(x), 0, Math.PI );
MathUtilities.integrationTest(Math::exp(x), 2, 20 );
 Type of a method reference?
Is not known until you try to assign it to a variable, in which case its
type is whatever interface that variable expected.
Ex: Math::sin could be different types in different contexts, but all the
types would be single-method interfaces whose method could accept
a single double as an argument.
Example: IntegrationTest1.java
Lars A. Lemos 22
2.8 The java.util.function
Package
 Interfaces like Integratable widely used
 So, Java 8 should build in many common cases
 Java.util.function defines many simple functional(SAM)
interfaces
 Named according to arguments and return values
Ex: replace my Integratable with builtin DoubleUnaryOperator
 Look in API for the method names
Althoug lambdas don’t refer to method names, your code that uses
the lambdas will need to call the methods.
 Type of a method reference?
Lars A. Lemos 23
2.8 The java.util.function
Package
 Types given
 Samples
 IntPredicate(int n, boolean out)
 LongUnaryOperator(long in, long out)
 DoubleBinaryOperator(two double in, double out)
 Example
 DoubleBinaryOperator f = (d1, d2) -> Math.cos(d1 + d2);
 Genericized
 There are also generic interfaces (Function<T,R> , Predicate<T>)
with widespread applicability.
 And concrete methods like “compose” and “negate”
Lars A. Lemos 24
2.8 The java.util.function
Package
 In previous example, replace this
public static double integrate(Integratable function, ...) {
... function.eval(...);
....
 With this
public static double integrate(DoubleUnaryOperator function, ...) {
... function.applyAsDouble(...);
....
}
Example: MathUtils.java
 Then, omit definition of Integratable entirely
 Because DoubleUnaryOperator is a functional (SAM) interface
containing a method with same signature as the method of the
Integratable interface.
Lars A. Lemos 25
2.8 The java.util.function
Package
 General Case
 If you are tempted to create an interface purely to be used as
target for a lambda
 Look through java.util.function and see if one of the functional
(SAM) interfaces can be used instead.
• DoubleUnaryOperator, IntUnaryOperator, LongUnaryOperator
o double/int/long in, same type out
• DoubleBinaryOpeartor, IntBinaryOperator, LongBinaryOperator
o Two doubles/ints/longs in, same type out
• DoublePredicate, IntPredicate, LongPredicate
o double/int/long in, boolean out
• DoubleConsumer, IntConsumer , LongConsumer
o double/int/long in, void return type
• Genericized interfaces: Function, Predicate, Consumer, etc
Lars A. Lemos 26
2.9 Wrap Up
 We have lambdas
 Concise and succint
 Familiar to developers that know functional programming
 Fits well with new streams API
 Have method references
 Many functional interfaces built in
 Still not real functional programming
 Type is inner class that implements interface, not a function
 Must create or find interface 1st, must know method name.
 Cannot use mutable local variables
Lars A. Lemos 27
End of part I
Part II – Streams
Thank you for your patience….
larslemos@gmail.com
Lars Lemos
toplars
Lars A. Lemos 28

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Scala tutorial
Scala tutorialScala tutorial
Scala tutorial
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Java moderno java para Jedis episodio I
Java moderno  java para  Jedis  episodio IJava moderno  java para  Jedis  episodio I
Java moderno java para Jedis episodio I
 
Java 8
Java 8Java 8
Java 8
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 

Andere mochten auch

Towards a Principle-based Classification of Structural Design Smells
Towards a Principle-based Classification of Structural Design SmellsTowards a Principle-based Classification of Structural Design Smells
Towards a Principle-based Classification of Structural Design SmellsTushar Sharma
 
PHAME: Principles of Hierarchy Abstraction Modularization and Encapsulation
PHAME: Principles of Hierarchy Abstraction Modularization and EncapsulationPHAME: Principles of Hierarchy Abstraction Modularization and Encapsulation
PHAME: Principles of Hierarchy Abstraction Modularization and EncapsulationTushar Sharma
 
Tools for refactoring
Tools for refactoringTools for refactoring
Tools for refactoringTushar Sharma
 
Why care about technical debt?
Why care about technical debt?Why care about technical debt?
Why care about technical debt?Tushar Sharma
 
Infographic - Pragmatic Technical Debt Management
Infographic - Pragmatic Technical Debt ManagementInfographic - Pragmatic Technical Debt Management
Infographic - Pragmatic Technical Debt ManagementTushar Sharma
 
Pragmatic Technical Debt Management
Pragmatic Technical Debt ManagementPragmatic Technical Debt Management
Pragmatic Technical Debt ManagementTushar Sharma
 
Tools for Identifying and Addressing Technical Debt
Tools for Identifying and Addressing Technical DebtTools for Identifying and Addressing Technical Debt
Tools for Identifying and Addressing Technical DebtTushar Sharma
 
A Checklist for Design Reviews
A Checklist for Design ReviewsA Checklist for Design Reviews
A Checklist for Design ReviewsTushar Sharma
 
Refactoring for Software Design Smells: Managing Technical Debt
Refactoring for Software Design Smells: Managing Technical DebtRefactoring for Software Design Smells: Managing Technical Debt
Refactoring for Software Design Smells: Managing Technical DebtTushar Sharma
 
Applying Design Principles in Practice
Applying Design Principles in PracticeApplying Design Principles in Practice
Applying Design Principles in PracticeTushar Sharma
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design PatternsGanesh Samarthyam
 

Andere mochten auch (11)

Towards a Principle-based Classification of Structural Design Smells
Towards a Principle-based Classification of Structural Design SmellsTowards a Principle-based Classification of Structural Design Smells
Towards a Principle-based Classification of Structural Design Smells
 
PHAME: Principles of Hierarchy Abstraction Modularization and Encapsulation
PHAME: Principles of Hierarchy Abstraction Modularization and EncapsulationPHAME: Principles of Hierarchy Abstraction Modularization and Encapsulation
PHAME: Principles of Hierarchy Abstraction Modularization and Encapsulation
 
Tools for refactoring
Tools for refactoringTools for refactoring
Tools for refactoring
 
Why care about technical debt?
Why care about technical debt?Why care about technical debt?
Why care about technical debt?
 
Infographic - Pragmatic Technical Debt Management
Infographic - Pragmatic Technical Debt ManagementInfographic - Pragmatic Technical Debt Management
Infographic - Pragmatic Technical Debt Management
 
Pragmatic Technical Debt Management
Pragmatic Technical Debt ManagementPragmatic Technical Debt Management
Pragmatic Technical Debt Management
 
Tools for Identifying and Addressing Technical Debt
Tools for Identifying and Addressing Technical DebtTools for Identifying and Addressing Technical Debt
Tools for Identifying and Addressing Technical Debt
 
A Checklist for Design Reviews
A Checklist for Design ReviewsA Checklist for Design Reviews
A Checklist for Design Reviews
 
Refactoring for Software Design Smells: Managing Technical Debt
Refactoring for Software Design Smells: Managing Technical DebtRefactoring for Software Design Smells: Managing Technical Debt
Refactoring for Software Design Smells: Managing Technical Debt
 
Applying Design Principles in Practice
Applying Design Principles in PracticeApplying Design Principles in Practice
Applying Design Principles in Practice
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design Patterns
 

Ähnlich wie Java 8 lambdas expressions

Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New featuresSon Nguyen
 
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)
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Simon Ritter
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon Ritter
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 

Ähnlich wie Java 8 lambdas expressions (20)

Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
Java8
Java8Java8
Java8
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Scala tutorial
Scala tutorialScala tutorial
Scala tutorial
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
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
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
JAVA_BASICS.ppt
JAVA_BASICS.pptJAVA_BASICS.ppt
JAVA_BASICS.ppt
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 

Kürzlich hochgeladen

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Kürzlich hochgeladen (20)

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Java 8 lambdas expressions

  • 1. Lambda Expressions pt1 1.1 Getting Started with Java 8 1.2 Java 8 References 1.3 Quick review of Pre-Lambda Handlers 1.4. Functional Interface Annotation 1.5 Lambda Handlers 1.6 Why Java 8? 1.7 Wra-Up Lars A. Lemos 1
  • 2. 1.Getting Started,Setup and Review 1.1 Getting Started with Java 8 1.2 Java 8 References 1.3 Quick review of Pre-Lambda Handlers 1.4. Functional Interface Annotation 1.5 Lambda Handlers 1.6 Why Java 8? 1.7 Wra-Up Lars A. Lemos 2
  • 3. Starting point  Jdk 8 download, Jdk 8 Demos and Samples http://www.oracle.com/technetwork/java/javase/downloads/jdk8- downloads-2133151.html  More Info http://docs.oracle.com/javase/8/docs/ http://docs.oracle.com/javase/tutorial/java/javaOO/lambda expressions.html  IDE • IntelliJ IDEA 13 - : http://www.jetbrains.com/idea/download/ • Netbeans 8 : https://netbeans.org/downloads/ • Eclipse Kepler : https://www.eclipse.org/downloads/ Lars A. Lemos 3 1.1 Getting Started with Java 8
  • 4.  Books Functional Programming in Java - Venkat Subramanian Java 8 Lambdas: Pragmatic Functional Programming – Richard Warburton Java SE 8 for the Really Impatient – Cay S. Horstman Java The Complete Reference 9th Ed – Herbert Schildt Lars A. Lemos 4 1.2 Java 8 References
  • 5. 1.3 Quick review of Pre-Lambda Handlers  Anonymous inner classess  Idea You need code to respond a button click, to run in the background for threads, or to handle sorting comparisons.  Pre-lambda alternatives  Separete class • Arrays.sort(theArray, new SeparateClass(...));  Main class(which implements interface) • Arrays.sort(theArray, this);  Named inner class • Arrays.sort(theArray, new InnerClass(...));  Anonymous inner class • Arrays.sort(theArray, new Comparator<String>(){...}); Lars A. Lemos 5
  • 6. 1.3 Quick review of Pre-Lambda Handlers  Separete class public class StringSorter1 { public void doTests() { String[] testStrings = {"one","two","three","four"}; System.out.println("Original: "); ArrayUtils.printArray(testStrings); Arrays.sort(testStrings, new StringLengthComparator()); System.out.println("After sorting by length: "); ArrayUtils.printArray(testStrings); Arrays.sort(testStrings, new LastLetterComparator()); System.out.println("After sorting by last letter: "); ArrayUtils.printArray(testStrings); }} Example: StringSorter1.java  Advantages • Flexible: can pass arguments to class constructor • More reusable: loosely coupled  Disadavantages • Need extra stpes to call method in main app. How does handler call method in main app? • It needs reference to the main app to do so. Lars A. Lemos 6
  • 7. 1.3 Quick review of Pre-Lambda Handlers  Implementing Interface  Advantages • No extra steps need to call methods in the main app. o The code is part of the main app, so it can call any method or access any instance variable, even private ones. • Simple o Widely used in real life for button handlers, when you know you will have only one button, or for threading code, when you need one method to run in the background.  Disadavantages • Inflexible: hard to have multiple different versions, since you cannot pass argumens to the handler. o For example, if you want to sort array using two or more ways? If you pass “this” to the second argument in Arrays.sort, it will refer to the same “compare” method both times. Lars A. Lemos 7
  • 8. 1.3 Quick review of Pre-Lambda Handlers  Named Inner Class  Advantages • No extra steps need to call methods in the main app.Inner class have full access to all methods and instances variables of surrounding class, including private ones. o However if there is a name conflict, it is necessary to use the unpopular OuterClass.this.name syntax. • Flexible: can define constructor and pass arguments.  Disadavantages o A bit harder to understand.  Anonymous Inner Class  Advantages • Full access to code of surrounding class (even private methods and variables). • Slightly more concice than named inner class(but still bulk and verbose).  Disadavantages o Harder to understand o Not reusable(cannot use the anonymous class definition in more). Example: StringSorter3.java Lars A. Lemos 8
  • 9. 1.4 @FunctionalInterface Annotation  @FunctionalInterface  Tells the compiler you intend this to be a functional Single Abstract Method (SAM) interface  One with exactly one abstract method  Thus, for which lambdas can be used.  Check performed at compile time  Also informs others developers that lambdas can be used for this interface  Analogous to @Override  Does extra work at compile time, but no difference at run time (assuming it passes the check)  Goals  Simple numerical integration using rectangle (mid-point) rule  Use lambdas for function to be integrated. Convenient and succinct. Example: SimpleInterface.java , TestInterface.java Lars A. Lemos 9
  • 10. 1.3 Lambda Handlers  Desired features  Full access to code from surrounding class  No confusion about meaning of “this”  Much more concise, succinct, and readable  Enourage a functional programming style  Lambda Arrays.sort(testStrings, (s1, s2) -> s1.length() – s2.length());  What is the under the hood implementation Arrays.sort(testStrings, new Comparator<String>() { @Override public int compare(string s1, String s2) { s1.length() – s2.length()); } }); Lars A. Lemos 10
  • 11. 1.4 Why Java 8 and Lambdas ?  Weakly (and usually dynamically ) typed  JavaScript, Lisp, Scheme, etc.  Strongly typed  Ruby, Scala, Clojure, etc.  Functional approach proven concise, useful, and parallelizable  Concise syntax(clear than anonymous inner classes)  Convienent for new streams library  Shapes.forEach(s -> s.setColor(Color.RED));  Similar constructs used in other languages  Callbacks, closures, map/reduce idiom  Step toward true functional programming  When funct. Prog approach is used, many classes of problems are easier to solve and result in code that is clearer to read and simpler to maintain. Lars A. Lemos 11
  • 12. 2. Lambdas Basics 2.1 Lambdas Expressions 2.2 Type Inferencing 2.3 Implied Return Values 2.4 Omitting Parents for One-Arg Lambdas 2.5 Effectively Final Local Variables 2.6 @FunctionalInterface Annotation 2.7 Method References 2.8 The java.util.function Package 2.9 Wrap Up Lars A. Lemos 12
  • 13. 2.1 Lambada Expressions  Replace this new SometInterface () { @Override public someType someMethod(args) { body; } }  With this (args) - > { body }  Example Array.sort(testStrings, new Comparator<String> () ) { @Override public int compare(String s1, String s2) { return (s1.length() – s2.length()); } Array.sort(testStrings, (String s1, String s2) - > { return (s1.length() – s2.length() ) ; } ) ; Example: JavaLambdas.java Lars A. Lemos 13
  • 14. 2.1 Lambada Expressions Part 1Basics  Old button.addActionListener (new ActionListener () { @Override public void actionPerformed(ActionEvent event) { action(); } });  New button.addActionListener(event -> action());  You get an Instance of an inner class that implements interface  The expected type must be an interface that has exactly one (abstract).  It’s called “Functional Interface” or “Single Abstract Method” (SAM) Example: ButtonFrame1.java Lars A. Lemos 14
  • 15. 2.2 Type Inferencing  Types in argument list can usually be omitted  Since Java usually already knows the expected parameter types for the single method of the functional interface (SAM interface)  Basic lambda (Type1 var1, Type2 var 2 …) - > { method body }  Lambda with type inference ( var1, var 2 …) - > { method body } Lars A. Lemos 15
  • 16. 2.2 Type Inferencing  Replace this new SometInterface () { @Override public someType someMethod( T1 v1, T2 v2 ) { body; } }  With this (v1, v2) - > { body } Array.sort(testStrings, new Comparator<String> () ) { @Override public int compare(String s1, String s2) { return (s1.length() – s2.length()); } Array.sort(testStrings, (s1, s2) - > { return (s1.length() – s2.length() ) ; } ) ; Example: JavaLambdas.java Lars A. Lemos 16
  • 17. 2.3 Implied Return Values  For body, use expression instead of block  Value of expression will be the return value, with no explicit “return” needed  If method has a void return type, then automatically no return value  Since lambdas are usually used only when method body is short, this approach (using expression instead of block ) is very common.  Previous Version (var1, var2) - > { return (something); }  Lambda with expression for body (var1, var2) - > { something } Example: JavaLambdas.java Lars A. Lemos 17
  • 18. 2.4 Omitting Parents for One-Arg Lambdas  If method take single argument, parents optional  No type should be used: you must let Java infer the type.  Ommiting types is normal practice  Previous Version ( varName ) - > someResult()  Lambda with parentheses omitted var - > someResult() Example: ButtonFrame3.java Lars A. Lemos 18
  • 19. 2.5 Effectively Final Local Variables  Lambdas can refer to local variables that are not declared final (but are never modified)  This is known as “effectively final” – variables where it would have been legal to declare them final.  You can still refer to mutable instance variables.  “this” in a lambda refers to main class, not inner class that was created for the lambda. There is no OuterClass.this. Also, no new level of scoping.  With explicit declaration final String s = “…”; doSomething(someArg - > use(s) );  Effectively final String s = “…”; doSomething(someArg - > use(s) ); Example: ButtonFrame4.java Lars A. Lemos 19
  • 20. 2.6 @FunctionalInterface Annotation 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); Example: MathUtilities.java Lars A. Lemos 20
  • 21. 2.7 Method References  Use ClassName:: staticMethodName or variable::instanceMethodName for lambdas  Ex: Math::cos or myVar::myMethod  The function must match signature of method in functional (SAM) interface to which it is assigned.  The type is found only from the context  The type of a method reference depends on what it is assigned to. This is always true with lambdas, but more obvious here.  Ex: no predifined type for Math::cos Lars A. Lemos 21
  • 22. 2.7 Method References  In previous example, replace MathUtilities.integrationTest(x-> Math.sin(x), 0, Math.PI ); MathUtilities.integrationTest(x-> Math.exp(x), 2, 20 );  With these MathUtilities.integrationTest( Math::sin(x), 0, Math.PI ); MathUtilities.integrationTest(Math::exp(x), 2, 20 );  Type of a method reference? Is not known until you try to assign it to a variable, in which case its type is whatever interface that variable expected. Ex: Math::sin could be different types in different contexts, but all the types would be single-method interfaces whose method could accept a single double as an argument. Example: IntegrationTest1.java Lars A. Lemos 22
  • 23. 2.8 The java.util.function Package  Interfaces like Integratable widely used  So, Java 8 should build in many common cases  Java.util.function defines many simple functional(SAM) interfaces  Named according to arguments and return values Ex: replace my Integratable with builtin DoubleUnaryOperator  Look in API for the method names Althoug lambdas don’t refer to method names, your code that uses the lambdas will need to call the methods.  Type of a method reference? Lars A. Lemos 23
  • 24. 2.8 The java.util.function Package  Types given  Samples  IntPredicate(int n, boolean out)  LongUnaryOperator(long in, long out)  DoubleBinaryOperator(two double in, double out)  Example  DoubleBinaryOperator f = (d1, d2) -> Math.cos(d1 + d2);  Genericized  There are also generic interfaces (Function<T,R> , Predicate<T>) with widespread applicability.  And concrete methods like “compose” and “negate” Lars A. Lemos 24
  • 25. 2.8 The java.util.function Package  In previous example, replace this public static double integrate(Integratable function, ...) { ... function.eval(...); ....  With this public static double integrate(DoubleUnaryOperator function, ...) { ... function.applyAsDouble(...); .... } Example: MathUtils.java  Then, omit definition of Integratable entirely  Because DoubleUnaryOperator is a functional (SAM) interface containing a method with same signature as the method of the Integratable interface. Lars A. Lemos 25
  • 26. 2.8 The java.util.function Package  General Case  If you are tempted to create an interface purely to be used as target for a lambda  Look through java.util.function and see if one of the functional (SAM) interfaces can be used instead. • DoubleUnaryOperator, IntUnaryOperator, LongUnaryOperator o double/int/long in, same type out • DoubleBinaryOpeartor, IntBinaryOperator, LongBinaryOperator o Two doubles/ints/longs in, same type out • DoublePredicate, IntPredicate, LongPredicate o double/int/long in, boolean out • DoubleConsumer, IntConsumer , LongConsumer o double/int/long in, void return type • Genericized interfaces: Function, Predicate, Consumer, etc Lars A. Lemos 26
  • 27. 2.9 Wrap Up  We have lambdas  Concise and succint  Familiar to developers that know functional programming  Fits well with new streams API  Have method references  Many functional interfaces built in  Still not real functional programming  Type is inner class that implements interface, not a function  Must create or find interface 1st, must know method name.  Cannot use mutable local variables Lars A. Lemos 27
  • 28. End of part I Part II – Streams Thank you for your patience…. larslemos@gmail.com Lars Lemos toplars Lars A. Lemos 28