SlideShare a Scribd company logo
2
Most read
3
Most read
6
Most read
Lambda Expressions in Java
Erhan Bagdemir
bagdemir.com - Follow on @ebagdemir
February 11, 2015
1 / 19
Today’s Agenda
Definition of Lambda.
Lambda Expressions in Java.
Functional Interfaces
Method References :: Operator
forEach()
Streams
2 / 19
Lambda Expressions: Definition of Lambda
A formal system for expressing
computational behaviour.
Invented by Alonzo Church in 1930.
Lambda expressions consist of many
parentheses i.e in Y-Combinator:
Y = λf .(λx.f (xx))(λx.f (xx))
3 / 19
Lambda Expressions: The Idea, behind
Functions are first-class citizens.
Lambda expressions are high order
functions:
They take other functions as a parameter.
They may return functions.
The functions in Lambda all referentially
transparent (pure functions). They:
provide a better parallelisation (no side-effects),
are easier to test,
are cacheable and provide lazy evaluation.
4 / 19
Lambda Expressions: Java 8
Some examples of function definitions:
in Javascript : function () { return x + 1 };
in LISP: (lambda (x) x + 1)
in C++11: [](int x) { return x + 1; }
in Scala: x => x + 1 or just _ + 1
in Java 8: (int x) -> x + 1
5 / 19
Lambda Expressions: Type of Lambda Expressions
Types of lambda expressions are defined in the java.util.function
Function<Integer, String> toStr = x -> Integer.parseValue(x);
You can pass lambdas as a parameter:
final Double forNetPrice = 50.0d;
final Function<Double, Double> withVAT = x -> x * 1.19;
prepareForShipment(withVAT, forPrice);
6 / 19
Lambda Expressions: Type of Lambda Expressions
If there is no functional interface in the java.util.function package
for your usage, create your own:
@FunctionalInterface
public interface WorkflowLambda {
IAsset execute(String clientId, String userId, MetadataView
view);
}
WorkflowLambda workflow = (clientId, userId, view) ->
executeWith(clientId, userId, view);
Call Functional Interfaces or Single Abstract Method interfaces.
7 / 19
Lambda Expressions: Scope of Lambda Expressions
The scope of lambda expressions, the scope of the enclosing type:
@Service
public class OrderManagement {
@Inject
private ShippingCostService scService;
private void calculateOrder() {
/* final */ double vatRate = vatService.getVAT(Country.DE);
Function<Double, Double> total = x -> (x * vatRate) +
this.scService.getCost();
}
}
Local variables can be referenced by lambda expressions, as long as
they are effective final.
8 / 19
Lambda Expressions: Method References
We can use methods of existing classes as lambda expressions.
Method references are syntactic shortcuts to the lambda expressions:
// static <T> void sort(T[] a, Comparator<? super T> c)
Collections.sort(myList, (firstInt, secondInt) -> firstInt -
secondInt);
Collections.sort(myList, ExistingComparator::compare);
// if we’d an existing comparator
public class ExistingComparator {
public static Integer compare(Integer first, Integer second) {
return first - second;
}
}
9 / 19
Lambda Examples: forEach()
Collections know how to iterate through their elements.
It’s a better style, which provides functional polymorphism, in
comparison to imperative external loops.
final List<Integer> myList = new ArrayList<>(3);
myList.add(1);
myList.add(5);
myList.add(2);
myList.forEach(System.out::println);
A new method in the "Collection" interface without breaking code?
10 / 19
Lambda Examples: Default Implementations
Interfaces may have default implementations:
public interface Dog {
public void wagTail();
public default void bark() {
System.out.println("Bark!");
}
}
The interfaces may contain static methods as well.
11 / 19
Lambda Examples: Streams
Streams
12 / 19
Lambda Examples: Streams
Streams represent a sequence of elements, which support different
operations that perform computations on these elements.
There are two types of operations:
Intermediate Operations (filter, sort, etc.).
Terminal Operations (collect, forEach, reduce, etc.)
Stream features:
No storage.
Functional in nature (No side-effects).
Streams are lazy (except sort).
Allowed to be unbounded.
Consumable.
Streams are monads!
13 / 19
Lambda Examples: Stream Pipelines
The processing pipeline consists of a source, intermediate operations
and a terminal operation.
14 / 19
Lambda Examples: Stream Processing
15 / 19
Lambda Examples: Streams
Stream sources: Arrays, Collections, Generators and I/O Streams,
e.g:
try (BufferedReader br = new BufferedReader(new
InputStreamReader(is))) {
br.lines().forEach(System.out::println);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
After a terminal operation, the stream is considered to be
consumed.
Intermediate operations are lazy and always return a new stream.
(see Example 6)
16 / 19
Lambda Examples: Code Samples
Some examples (https://github.com/bagdemir/java8-training) :
Generators
Comparators
File I/O
Regular Expressions
Reducer
Collectors
Parallel Streams
17 / 19
Lambda Examples: Finish
Functional Programming (in Scala)
Structure and Interpretation of
Computer Programs
18 / 19
Links
Lambda Quick Start
Oracle.com : http://bit.ly/1eR0we0
-
Streams
Oracle.com : http://bit.ly/1eh4aZo
Oracle.com : http://bit.ly/1ustKrM
-
Contact
https://github.com/bagdemir
https://twitter.com/ebagdemir
http://www.bagdemir.com
19 / 19

More Related Content

What's hot (20)

PDF
Java 8 features
NexThoughts Technologies
 
PPTX
Lambda Expressions in Java 8
icarter09
 
PPTX
Java 8 - Features Overview
Sergii Stets
 
PPT
Java 8 Streams
Manvendra Singh
 
PPTX
Java 8 presentation
Van Huong
 
PDF
Java 8 lambda expressions
Logan Chien
 
PDF
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
PDF
Generics
Ravi_Kant_Sahu
 
PPT
Major Java 8 features
Sanjoy Kumar Roy
 
PDF
Java 8 Stream API. A different way to process collections.
David Gómez García
 
ODP
Java 9 Features
NexThoughts Technologies
 
PPTX
Spring Boot and REST API
07.pallav
 
PPT
Java interfaces
Raja Sekhar
 
PPS
Introduction to class in java
kamal kotecha
 
PDF
Introduction to RxJS
Brainhub
 
PPTX
20.4 Java interfaces and abstraction
Intro C# Book
 
PDF
Quick introduction to scala
Mohammad Hossein Rimaz
 
PPTX
Java 8 features
Maýur Chourasiya
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPTX
Java Methods
OXUS 20
 
Java 8 features
NexThoughts Technologies
 
Lambda Expressions in Java 8
icarter09
 
Java 8 - Features Overview
Sergii Stets
 
Java 8 Streams
Manvendra Singh
 
Java 8 presentation
Van Huong
 
Java 8 lambda expressions
Logan Chien
 
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Generics
Ravi_Kant_Sahu
 
Major Java 8 features
Sanjoy Kumar Roy
 
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Java 9 Features
NexThoughts Technologies
 
Spring Boot and REST API
07.pallav
 
Java interfaces
Raja Sekhar
 
Introduction to class in java
kamal kotecha
 
Introduction to RxJS
Brainhub
 
20.4 Java interfaces and abstraction
Intro C# Book
 
Quick introduction to scala
Mohammad Hossein Rimaz
 
Java 8 features
Maýur Chourasiya
 
Introduction to Javascript
Amit Tyagi
 
Java Methods
OXUS 20
 

Viewers also liked (8)

PDF
Working With Concurrency In Java 8
Heartin Jacob
 
PDF
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
PDF
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
PDF
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
PPTX
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
PDF
Parallel streams in java 8
David Gómez García
 
PPTX
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
PDF
Real World Java 9
Trisha Gee
 
Working With Concurrency In Java 8
Heartin Jacob
 
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
Parallel streams in java 8
David Gómez García
 
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
Real World Java 9
Trisha Gee
 
Ad

Similar to Lambda Expressions in Java (20)

PDF
Java 8
Sheeban Singaram
 
PPTX
Java Advanced Topic - Java Lambda Expressions.pptx
MuraliD32
 
PDF
Lambdas in Java 8
Tobias Coetzee
 
PDF
Presentation lambda calculus in java
Mahdi Cherif
 
PDF
Jf12 lambdas injava8-1
langer4711
 
PDF
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
PDF
Programming with Lambda Expressions in Java
langer4711
 
PDF
Java8
Felipe Mamud
 
PPTX
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
Simon Ritter
 
PDF
Unit-3.pptx.pdf java api knowledge apiii
mpfbaa
 
PPTX
Week-1..................................
kmjanani05
 
PDF
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 
PPTX
New features in jdk8 iti
Ahmed mar3y
 
PDF
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
PPTX
What's New in Java 8
javafxpert
 
PDF
Lambda Functions in Java 8
Ganesh Samarthyam
 
PPTX
Lambdas, Collections Framework, Stream API
Prabu U
 
PDF
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
PPTX
Simple Lambdas in java in oca 8.0 on feb
krishmf1
 
PDF
What's new in java 8
Dian Aditya
 
Java Advanced Topic - Java Lambda Expressions.pptx
MuraliD32
 
Lambdas in Java 8
Tobias Coetzee
 
Presentation lambda calculus in java
Mahdi Cherif
 
Jf12 lambdas injava8-1
langer4711
 
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Programming with Lambda Expressions in Java
langer4711
 
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
Simon Ritter
 
Unit-3.pptx.pdf java api knowledge apiii
mpfbaa
 
Week-1..................................
kmjanani05
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Ganesh Samarthyam
 
New features in jdk8 iti
Ahmed mar3y
 
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
What's New in Java 8
javafxpert
 
Lambda Functions in Java 8
Ganesh Samarthyam
 
Lambdas, Collections Framework, Stream API
Prabu U
 
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
Simple Lambdas in java in oca 8.0 on feb
krishmf1
 
What's new in java 8
Dian Aditya
 
Ad

Recently uploaded (20)

PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 

Lambda Expressions in Java

  • 1. Lambda Expressions in Java Erhan Bagdemir bagdemir.com - Follow on @ebagdemir February 11, 2015 1 / 19
  • 2. Today’s Agenda Definition of Lambda. Lambda Expressions in Java. Functional Interfaces Method References :: Operator forEach() Streams 2 / 19
  • 3. Lambda Expressions: Definition of Lambda A formal system for expressing computational behaviour. Invented by Alonzo Church in 1930. Lambda expressions consist of many parentheses i.e in Y-Combinator: Y = λf .(λx.f (xx))(λx.f (xx)) 3 / 19
  • 4. Lambda Expressions: The Idea, behind Functions are first-class citizens. Lambda expressions are high order functions: They take other functions as a parameter. They may return functions. The functions in Lambda all referentially transparent (pure functions). They: provide a better parallelisation (no side-effects), are easier to test, are cacheable and provide lazy evaluation. 4 / 19
  • 5. Lambda Expressions: Java 8 Some examples of function definitions: in Javascript : function () { return x + 1 }; in LISP: (lambda (x) x + 1) in C++11: [](int x) { return x + 1; } in Scala: x => x + 1 or just _ + 1 in Java 8: (int x) -> x + 1 5 / 19
  • 6. Lambda Expressions: Type of Lambda Expressions Types of lambda expressions are defined in the java.util.function Function<Integer, String> toStr = x -> Integer.parseValue(x); You can pass lambdas as a parameter: final Double forNetPrice = 50.0d; final Function<Double, Double> withVAT = x -> x * 1.19; prepareForShipment(withVAT, forPrice); 6 / 19
  • 7. Lambda Expressions: Type of Lambda Expressions If there is no functional interface in the java.util.function package for your usage, create your own: @FunctionalInterface public interface WorkflowLambda { IAsset execute(String clientId, String userId, MetadataView view); } WorkflowLambda workflow = (clientId, userId, view) -> executeWith(clientId, userId, view); Call Functional Interfaces or Single Abstract Method interfaces. 7 / 19
  • 8. Lambda Expressions: Scope of Lambda Expressions The scope of lambda expressions, the scope of the enclosing type: @Service public class OrderManagement { @Inject private ShippingCostService scService; private void calculateOrder() { /* final */ double vatRate = vatService.getVAT(Country.DE); Function<Double, Double> total = x -> (x * vatRate) + this.scService.getCost(); } } Local variables can be referenced by lambda expressions, as long as they are effective final. 8 / 19
  • 9. Lambda Expressions: Method References We can use methods of existing classes as lambda expressions. Method references are syntactic shortcuts to the lambda expressions: // static <T> void sort(T[] a, Comparator<? super T> c) Collections.sort(myList, (firstInt, secondInt) -> firstInt - secondInt); Collections.sort(myList, ExistingComparator::compare); // if we’d an existing comparator public class ExistingComparator { public static Integer compare(Integer first, Integer second) { return first - second; } } 9 / 19
  • 10. Lambda Examples: forEach() Collections know how to iterate through their elements. It’s a better style, which provides functional polymorphism, in comparison to imperative external loops. final List<Integer> myList = new ArrayList<>(3); myList.add(1); myList.add(5); myList.add(2); myList.forEach(System.out::println); A new method in the "Collection" interface without breaking code? 10 / 19
  • 11. Lambda Examples: Default Implementations Interfaces may have default implementations: public interface Dog { public void wagTail(); public default void bark() { System.out.println("Bark!"); } } The interfaces may contain static methods as well. 11 / 19
  • 13. Lambda Examples: Streams Streams represent a sequence of elements, which support different operations that perform computations on these elements. There are two types of operations: Intermediate Operations (filter, sort, etc.). Terminal Operations (collect, forEach, reduce, etc.) Stream features: No storage. Functional in nature (No side-effects). Streams are lazy (except sort). Allowed to be unbounded. Consumable. Streams are monads! 13 / 19
  • 14. Lambda Examples: Stream Pipelines The processing pipeline consists of a source, intermediate operations and a terminal operation. 14 / 19
  • 15. Lambda Examples: Stream Processing 15 / 19
  • 16. Lambda Examples: Streams Stream sources: Arrays, Collections, Generators and I/O Streams, e.g: try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) { br.lines().forEach(System.out::println); } catch (Exception e) { System.out.println(e.getMessage()); } After a terminal operation, the stream is considered to be consumed. Intermediate operations are lazy and always return a new stream. (see Example 6) 16 / 19
  • 17. Lambda Examples: Code Samples Some examples (https://github.com/bagdemir/java8-training) : Generators Comparators File I/O Regular Expressions Reducer Collectors Parallel Streams 17 / 19
  • 18. Lambda Examples: Finish Functional Programming (in Scala) Structure and Interpretation of Computer Programs 18 / 19
  • 19. Links Lambda Quick Start Oracle.com : http://bit.ly/1eR0we0 - Streams Oracle.com : http://bit.ly/1eh4aZo Oracle.com : http://bit.ly/1ustKrM - Contact https://github.com/bagdemir https://twitter.com/ebagdemir http://www.bagdemir.com 19 / 19