SlideShare a Scribd company logo
Functional programming in Java 8
07 juli 2016
Masudul Haque
Adapt : Learn functional programming
Java meets functional
programming (with
lambdas)
Java is not your grandma’s language anymore!
What is Lambda?
Before Lambda
List<Employee> employees = ...
double highestSalary = 0.0;
for (Employee e : employees) {
if (e.year == 2016) {
if (e.salary > highestSalary) {
highestSalary = e.salary;
}
}
}
• Client controls iteration
• Inherently serial: iterate from
beginning to end
• Not thread-safe
After Lambda
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
• More readable
• More abstract
• Less error-prone
• No reliance on mutable state
• Easier to make parallel
What is Lambda?
• Lambda expressions represent anonymous functions
– Like a method, has a typed argument list, a return type, a set of thrown exceptions, and
a body
– Not associated with a class
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
Predicate
Function
What is Lambda?
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
• Stream<T> filter(Predicate<? super T> predicate)
• Filter objects that match a Predicate object
• <R> Stream<R> map(Function<? super T, ? extends R> mapper)
• Map objects to another value as specified by a Function object
Predicate
Function
What is Functional programming?
• Functional languages view programs as an entity— called a function—
that accepts inputs and produces output
• Functions are connected together by their outputs to other functions’
inputs.
• Underlying approach: “Evaluate an expression. Then use the results for
something else.”
Example
Runnable r = new Runnable(){
public void run(){
System.out.println("Hello World");
}
};
Runnable r =()-> System.out.println("Hello World");
Stream
What is Stream?
• A Typed Interface.
public interface Stream<T> extends BaseStream<T,Stream<T>>
• Abstraction for specifying aggregate computations
– Not a data structure
– Can be infinite
• Simplifies the description of aggregate computations
– Exposes opportunitires for optimisation
– Fusing, laziness and parrallelism
What is Stream?
• What can I do with it?
Answer: efficiently process high volumes of data, but also small ones.
• What does efficiently mean?
Two things:
1. In parallel, to leverage multicore CPU
2. In pipeline, to avoid the computation of intermediate data structures
Stream Pipeline
A stream pipeline consists of three types of things
1. A source
2. Zero or more intermediate operations
3. A terminal operation
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max(); Intemediate
Operation
Source
Terminal
Operation
Intemediate
Operations
stream pipeline
Stream
source
Intermediate
operations
Terminal
operation
stream
stream
Examples:
IntStream.range(),
Arrays.stream()
Examples:
map(), filter(),
distinct(), sorted()
Examples:
sum(), collect(),
forEach(), reduce()
DoubleStream.
of(1.0, 4.0, 9.0)
map(Math::sqrt)
.peek(System.out::
println)
Stream
Source (with
elements 1.0,
4.0, and 9.0)
Intermediate
Operation 1
(maps to
element values
1.0, 2.0, and 3.0)
Intermediate
Operation 2
(prints 1.0, 2.0,
and 3.0)
.sum();
Terminal
Operation
(returns the
sum 6.0)
DoubleStream.of(1.0, 4.0, 9.0)
.map(Math::sqrt)
.peek(System.out::println)
.sum();
Stream.of (1, 2, 3, 4, 5)
.map(i -> i * i)
.peek(i -> System.out.printf("%d ",i))
.count();
prints: 1 4 9 16 25
Demo
long startTime = System.currentTimeMillis();
long numOfPrimes = LongStream.rangeClosed(2, 10_000_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
long endTime = System.currentTimeMillis();
System.out.printf( " Duration : %f %n ",(endTime - startTime)/1000.0);
Parallel code
Serial code
long numOfPrimes =LongStream.rangeClosed(2, 10_000_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 664579
8.501 seconds
Parallel code
Serial code
Let’s flip the switch by
calling parallel() function
long numOfPrimes =LongStream.rangeClosed(2, 10_000_000)
.parallel()
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 664579
2.041 seconds
Wow! That’s an awesome flip
switch!
Internally, parallel streams make
use of fork-join framework
Q & A
Contact
For any question
Email: M.Haque@cimsolutions.nl
Follow me in following site:
Stackoverflow
http://stackoverflow.com/users/1265660/masud
Github
https://github.com/masudcse05
Blog
https://masudulhaque.wordpress.com

More Related Content

What's hot

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
Harmeet Singh(Taara)
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
langer4711
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
Rob Knight
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
Building Data Mapper PHP5
Building Data Mapper PHP5Building Data Mapper PHP5
Building Data Mapper PHP5
Vance Lucas
 

What's hot (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
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Building Data Mapper PHP5
Building Data Mapper PHP5Building Data Mapper PHP5
Building Data Mapper PHP5
 

Similar to Java 8 lambda

Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
Java 8
Java 8Java 8
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
BArulmozhi
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
Java8
Java8Java8
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8
Simon Ritter
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
Mohsen Zainalpour
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response times
Yan Cui
 
Java 8
Java 8Java 8
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Spark Summit
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 

Similar to Java 8 lambda (20)

Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Java 8
Java 8Java 8
Java 8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
 
Java 8
Java 8Java 8
Java 8
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java8
Java8Java8
Java8
 
Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8Lessons Learnt With Lambdas and Streams in JDK 8
Lessons Learnt With Lambdas and Streams in JDK 8
 
java8
java8java8
java8
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response times
 
Java 8
Java 8Java 8
Java 8
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
 
Oct.22nd.Presentation.Final
Oct.22nd.Presentation.FinalOct.22nd.Presentation.Final
Oct.22nd.Presentation.Final
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 

More from Masudul Haque

Websocket
WebsocketWebsocket
Websocket
Masudul Haque
 
Java 9 new features
Java 9 new featuresJava 9 new features
Java 9 new features
Masudul Haque
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular ExpressionMasudul Haque
 

More from Masudul Haque (6)

Websocket
WebsocketWebsocket
Websocket
 
Java 9 new features
Java 9 new featuresJava 9 new features
Java 9 new features
 
Java-7: Collections
Java-7: CollectionsJava-7: Collections
Java-7: Collections
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Java-7 Concurrency
Java-7 ConcurrencyJava-7 Concurrency
Java-7 Concurrency
 
Basic java
Basic javaBasic java
Basic java
 

Recently uploaded

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 

Recently uploaded (20)

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 

Java 8 lambda

  • 1. Functional programming in Java 8 07 juli 2016 Masudul Haque
  • 2. Adapt : Learn functional programming
  • 4. Java is not your grandma’s language anymore!
  • 6. Before Lambda List<Employee> employees = ... double highestSalary = 0.0; for (Employee e : employees) { if (e.year == 2016) { if (e.salary > highestSalary) { highestSalary = e.salary; } } } • Client controls iteration • Inherently serial: iterate from beginning to end • Not thread-safe
  • 7. After Lambda List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); • More readable • More abstract • Less error-prone • No reliance on mutable state • Easier to make parallel
  • 8. What is Lambda? • Lambda expressions represent anonymous functions – Like a method, has a typed argument list, a return type, a set of thrown exceptions, and a body – Not associated with a class List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); Predicate Function
  • 9. What is Lambda? List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); • Stream<T> filter(Predicate<? super T> predicate) • Filter objects that match a Predicate object • <R> Stream<R> map(Function<? super T, ? extends R> mapper) • Map objects to another value as specified by a Function object Predicate Function
  • 10. What is Functional programming? • Functional languages view programs as an entity— called a function— that accepts inputs and produces output • Functions are connected together by their outputs to other functions’ inputs. • Underlying approach: “Evaluate an expression. Then use the results for something else.”
  • 11. Example Runnable r = new Runnable(){ public void run(){ System.out.println("Hello World"); } }; Runnable r =()-> System.out.println("Hello World");
  • 13. What is Stream? • A Typed Interface. public interface Stream<T> extends BaseStream<T,Stream<T>> • Abstraction for specifying aggregate computations – Not a data structure – Can be infinite • Simplifies the description of aggregate computations – Exposes opportunitires for optimisation – Fusing, laziness and parrallelism
  • 14. What is Stream? • What can I do with it? Answer: efficiently process high volumes of data, but also small ones. • What does efficiently mean? Two things: 1. In parallel, to leverage multicore CPU 2. In pipeline, to avoid the computation of intermediate data structures
  • 15. Stream Pipeline A stream pipeline consists of three types of things 1. A source 2. Zero or more intermediate operations 3. A terminal operation List<Employee> employees = ... double highestSalary = employees.stream() .filter(Employee e-> e.getYear() == 2016) .map(e -> e.getSalary()) .max(); Intemediate Operation Source Terminal Operation Intemediate Operations
  • 17. DoubleStream. of(1.0, 4.0, 9.0) map(Math::sqrt) .peek(System.out:: println) Stream Source (with elements 1.0, 4.0, and 9.0) Intermediate Operation 1 (maps to element values 1.0, 2.0, and 3.0) Intermediate Operation 2 (prints 1.0, 2.0, and 3.0) .sum(); Terminal Operation (returns the sum 6.0) DoubleStream.of(1.0, 4.0, 9.0) .map(Math::sqrt) .peek(System.out::println) .sum();
  • 18. Stream.of (1, 2, 3, 4, 5) .map(i -> i * i) .peek(i -> System.out.printf("%d ",i)) .count(); prints: 1 4 9 16 25
  • 19. Demo long startTime = System.currentTimeMillis(); long numOfPrimes = LongStream.rangeClosed(2, 10_000_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); long endTime = System.currentTimeMillis(); System.out.printf( " Duration : %f %n ",(endTime - startTime)/1000.0);
  • 21. long numOfPrimes =LongStream.rangeClosed(2, 10_000_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 664579 8.501 seconds
  • 22. Parallel code Serial code Let’s flip the switch by calling parallel() function
  • 23. long numOfPrimes =LongStream.rangeClosed(2, 10_000_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 664579 2.041 seconds
  • 24. Wow! That’s an awesome flip switch!
  • 25. Internally, parallel streams make use of fork-join framework
  • 26. Q & A
  • 27. Contact For any question Email: M.Haque@cimsolutions.nl Follow me in following site: Stackoverflow http://stackoverflow.com/users/1265660/masud Github https://github.com/masudcse05 Blog https://masudulhaque.wordpress.com