SlideShare a Scribd company logo
1 of 40
Download to read offline
Functional Programming
in Java 8
Contents
• Lambda
• Stream
• Parallelization
• Asynchronization
Lambda
Higher-order Function
... is a function that does at least one of the following:
• Takes one or more functions as arguments
• Returns a function as its result
Cache<String, String> cache = CacheBuilder.newBuilder().build();
String sql = "SQL_1";
String result = cache.get(sql, new Callable<String>() {
@Override
public String call() throws Exception {
return "I am the syntax tree of " + sql;
}
}));
What is Lambda Expression?
Lambda is just a syntactic sugar, but it will change how you programing.
Cache<String, String> cache = CacheBuilder.newBuilder().build();
String sql = "SQL_1";
String result = cache.get(sql, new Callable<String>() {
@Override
public String call() throws Exception {
return "I am the syntax tree of " + sql;
}
}));
String result = cache.get(sql, () -> "I am the syntax tree of " + sql);
Closures
• sql is passed to this Callable. How?
Cache<String, String> cache = CacheBuilder.newBuilder().build();
String sql = "SQL_1";
String result = cache.get(sql, new Callable<String>() {
@Override
public String call() throws Exception {
return "I am the syntax tree of " + sql;
}
}));
String result = cache.get(sql, () -> "I am the syntax tree of " + sql);
• How to pass a function along with its context as an argument?
• (extend) How to implement a linked list with Closures?
Objects are poor man's closures.
Closures are poor man's objects.
Closures <=> Objects
Functional Interfaces
• Interfaces with only one abstract method.
• @FunctionalInterface
public interface ActionListener {
public void actionPerformed(ActionEvent event);
}
Logger + Lambda
Logger logger = new Logger();
if (logger.isDebugEnabled()) {
logger.debug("Look at this: " + expensiveOperation());
}
Logger logger = new Logger();
logger.debug(() -> "Look at this: " + expensiveOperation());
function is first class object in Functional Programing
Streams
Example
• Given List<Artist>
• Filter artists living in China
public final class Album {
private String name;
private List<Track> tracks;
private List<Artist> musicians;
}
public final class Artist {
private String name;
private List<Artist> members;
private String nationality;
}
public final class Track {
private final String name;
private final int length;
}
Without streams...
public List<Artist> artistsLivingInLondon() {
List<Artist> results = new ArrayList<>();
for (Artist artist : artists) {
if ("China".equals(artist.getNationality())) {
results.add(artist);
}
}
return results;
}
Example
• Given List<Artist>, filter artists living in China
• Given List<Artist>, return names of all artists
public List<Artist> artistsLivingInChina() {
return artists.stream()
.filter(artist -> "China".equals(artist.getNationality()))
.collect(Collectors.toList());
}
public List<String> getNamesOfArtists_MethodReference() {
return artists.stream()
.map(Artist::getName)
.collect(Collectors.toList());
}
Basic Operations
• map
• filter
• flatMap
• collect
• max/min
Refactoring
Set<String> findLongTracks(List<Album> albums)
Find all long tracks (length >= 60) in a list of albums
public final class Track {
private final String name;
private final int length;
}
Legacy Code
public Set<String> findLongTracks(List<Album> albums) {
Set<String> trackNames = new HashSet<>();
for(Album album : albums) {
for (Track track : album.getTrackList()) {
if (track.getLength() > 60) {
String name = track.getName();
trackNames.add(name);
}
}
}
return trackNames;
}
Step 1
public Set<String> findLongTracks(List<Album> albums) {
Set<String> trackNames = new HashSet<>();
albums.stream()
.forEach(album -> {
album.getTracks()
.forEach(track -> {
if (track.getLength() > 60) {
String name = track.getName();
trackNames.add(name);
}
});
});
return trackNames;
}
filter() map()
Step 2
public Set<String> findLongTracks(List<Album> albums) {
Set<String> trackNames = new HashSet<>();
albums.stream()
.forEach(album -> {
album.getTracks()
.filter(track -> track.getLength() > 60)
.map(track -> track.getName())
.forEach(name -> trackNames.add(name));
});
return trackNames;
}
flatMap()
Step 3
public Set<String> findLongTracks(List<Album> albums) {
Set<String> trackNames = new HashSet<>();
albums.stream()
.flatMap(album -> album.getTracks())
.filter(track -> track.getLength() > 60)
.map(track -> track.getName())
.forEach(name -> trackNames.add(name));
return trackNames;
}
Collectors
• toMap
• toList
• toSet
Step 4
public Set<String> findLongTracks(List<Album> albums) {
return albums.stream()
.flatMap(album -> album.getTracks())
.filter(track -> track.getLength() > 60)
.map(track -> track.getName())
.collect(toSet());
}
More Collectors
• counting
• reducing
• partitioningBy
• groupingBy
• joining
• maxBy
• minBy
...
public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) {
return albums.collect(groupingBy(album -> album.getMainMusician(),
counting()));
}
Downstream Collector
public Map<Artist, Integer> numberOfAlbumsDumb(Stream<Album> albums) {
Map<Artist, List<Album>> albumsByArtist
= albums.collect(groupingBy(album -> album.getMainMusician()));
Map<Artist, Integer> numberOfAlbums = new HashMap<>();
for(Entry<Artist, List<Album>> entry : albumsByArtist.entrySet()) {
numberOfAlbums.put(entry.getKey(), entry.getValue().size());
}
return numberOfAlbums;
}
Parallelization
stream.parallel()
public Map<Integer, Double> parallelDiceRolls() {
double fraction = 1.0 / N;
return IntStream.range(0, N)
.mapToObj(twoDiceThrows())
.collect(groupingBy(side -> side, summingDouble(n -> fraction)));
}
private static IntFunction<Integer> twoDiceThrows() {
return i -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int firstThrow = random.nextInt(1, 7);
int secondThrow = random.nextInt(1, 7);
return firstThrow + secondThrow;
};
}
stream.parallel()
public Map<Integer, Double> parallelDiceRolls() {
double fraction = 1.0 / N;
return IntStream.range(0, N)
.parallel()
.mapToObj(twoDiceThrows())
.collect(groupingBy(side -> side, summingDouble(n -> fraction)));
}
private static IntFunction<Integer> twoDiceThrows() {
return i -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int firstThrow = random.nextInt(1, 7);
int secondThrow = random.nextInt(1, 7);
return firstThrow + secondThrow;
};
}
ForkJoinPool
class Fibonacci extends RecursiveTask<Long> {
final Long n;
Fibonacci(Long n) {
this.n = n;
}
@Override
public Long compute() {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.compute() + f1.join();
}
}
ForkJoinPool
• Design for compute-intensive tasks
• Work stealing algorithm
• No blocking
Asynchronization
Problem of Futurue
• Call future.get() will block current thread
public Album lookupByName(String albumName) {
Future<Credentials> trackLogin = loginTo("track");
Future<Credentials> artistLogin = loginTo("artist");
try {
Future<List<Track>> tracks = lookupTracks(albumName, trackLogin.get());
Future<List<Artist>> artists = lookupArtists(albumName, artistLogin.get());
return new Album(albumName, tracks.get(), artists.get());
} catch (InterruptedException | ExecutionException e) {
throw new AlbumLookupException(e.getCause());
}
}
CompletableFuture
public Album lookupByName(String albumName) {
CompletableFuture<List<Artist>> artistLookup = loginTo("artist")
.thenCompose(artistLogin -> lookupArtists(albumName, artistLogin));
CompletableFuture<List<Track>> trackLookup = loginTo("track")
.thenCompose(trackLogin -> lookupTracks(albumName, trackLogin));
return trackLookup
.thenCombine(artistLookup,
(tracks, artists) -> new Album(albumName, tracks, artists))
.join();
}
Another side...
future.complete(artist);
future.completeExceptionally(new
AlbumLookupException("Cannot find " + name));
private CompletableFuture<List<Track>> lookupTracks(String albumName,
Credentials credentials) {
return CompletableFuture.supplyAsync(() -> {
sleep(1000);
return tracks;
}, service);
}
RxJava
Observable handles a stream of events
A Kind Reminder
• How to make everything functional?
• Pure Function
• Object
• Loop
• What is Curry?
• What is Y-combinator?
.....
Functional
Programming in Java
A Kind Reminder
• The Magic Book - SICP
Thanks!
Q&A

More Related Content

What's hot

JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?PROIDEA
 
Munihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMunihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMatthew Pickering
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Waytdc-globalcode
 
Ramda lets write declarative js
Ramda   lets write declarative jsRamda   lets write declarative js
Ramda lets write declarative jsPivorak MeetUp
 
Nik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReactNik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReactOdessaJS Conf
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemJohn De Goes
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 

What's hot (20)

JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Munihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMunihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template Haskell
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
Ramda lets write declarative js
Ramda   lets write declarative jsRamda   lets write declarative js
Ramda lets write declarative js
 
Nik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReactNik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReact
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Chirantan (or)
Chirantan  (or)Chirantan  (or)
Chirantan (or)
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
"Kotlin и rx в android" Дмитрий Воронин (Avito)
"Kotlin и rx в android" Дмитрий Воронин  (Avito)"Kotlin и rx в android" Дмитрий Воронин  (Avito)
"Kotlin и rx в android" Дмитрий Воронин (Avito)
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Meet scala
Meet scalaMeet scala
Meet scala
 

Similar to Functional Programming in Java 8

Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)RichardWarburton
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsNeo4j
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsMark Needham
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsNeo4j
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
 
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsGraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsNeo4j
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Isuru Samaraweera
 
public class EllipsoidList { private String list- private Array.pdf
public class EllipsoidList {     private String list-    private Array.pdfpublic class EllipsoidList {     private String list-    private Array.pdf
public class EllipsoidList { private String list- private Array.pdf3rdeyesolutions
 
A Tour of Building Web Applications with R Shiny
A Tour of Building Web Applications with R Shiny A Tour of Building Web Applications with R Shiny
A Tour of Building Web Applications with R Shiny Wendy Chen Dubois
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfmail931892
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaEdureka!
 

Similar to Functional Programming in Java 8 (20)

Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Java8lambda
Java8lambda Java8lambda
Java8lambda
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
JDK 8
JDK 8JDK 8
JDK 8
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & OperationsGraphTour - Utilizing Powerful Extensions for Analytics & Operations
GraphTour - Utilizing Powerful Extensions for Analytics & Operations
 
Hot Streaming Java
Hot Streaming JavaHot Streaming Java
Hot Streaming Java
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
 
public class EllipsoidList { private String list- private Array.pdf
public class EllipsoidList {     private String list-    private Array.pdfpublic class EllipsoidList {     private String list-    private Array.pdf
public class EllipsoidList { private String list- private Array.pdf
 
A Tour of Building Web Applications with R Shiny
A Tour of Building Web Applications with R Shiny A Tour of Building Web Applications with R Shiny
A Tour of Building Web Applications with R Shiny
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
 

More from 宇 傅

Parallel Query Execution
Parallel Query ExecutionParallel Query Execution
Parallel Query Execution宇 傅
 
The Evolution of Data Systems
The Evolution of Data SystemsThe Evolution of Data Systems
The Evolution of Data Systems宇 傅
 
The Volcano/Cascades Optimizer
The Volcano/Cascades OptimizerThe Volcano/Cascades Optimizer
The Volcano/Cascades Optimizer宇 傅
 
PelotonDB - A self-driving database for hybrid workloads
PelotonDB - A self-driving database for hybrid workloadsPelotonDB - A self-driving database for hybrid workloads
PelotonDB - A self-driving database for hybrid workloads宇 傅
 
Immutable Data Structures
Immutable Data StructuresImmutable Data Structures
Immutable Data Structures宇 傅
 
The Case for Learned Index Structures
The Case for Learned Index StructuresThe Case for Learned Index Structures
The Case for Learned Index Structures宇 傅
 
Spark and Spark Streaming
Spark and Spark StreamingSpark and Spark Streaming
Spark and Spark Streaming宇 傅
 
第三届阿里中间件性能挑战赛冠军队伍答辩
第三届阿里中间件性能挑战赛冠军队伍答辩第三届阿里中间件性能挑战赛冠军队伍答辩
第三届阿里中间件性能挑战赛冠军队伍答辩宇 傅
 
Data Streaming Algorithms
Data Streaming AlgorithmsData Streaming Algorithms
Data Streaming Algorithms宇 傅
 
Golang 101
Golang 101Golang 101
Golang 101宇 傅
 
Docker Container: isolation and security
Docker Container: isolation and securityDocker Container: isolation and security
Docker Container: isolation and security宇 傅
 
Paxos and Raft Distributed Consensus Algorithm
Paxos and Raft Distributed Consensus AlgorithmPaxos and Raft Distributed Consensus Algorithm
Paxos and Raft Distributed Consensus Algorithm宇 傅
 

More from 宇 傅 (12)

Parallel Query Execution
Parallel Query ExecutionParallel Query Execution
Parallel Query Execution
 
The Evolution of Data Systems
The Evolution of Data SystemsThe Evolution of Data Systems
The Evolution of Data Systems
 
The Volcano/Cascades Optimizer
The Volcano/Cascades OptimizerThe Volcano/Cascades Optimizer
The Volcano/Cascades Optimizer
 
PelotonDB - A self-driving database for hybrid workloads
PelotonDB - A self-driving database for hybrid workloadsPelotonDB - A self-driving database for hybrid workloads
PelotonDB - A self-driving database for hybrid workloads
 
Immutable Data Structures
Immutable Data StructuresImmutable Data Structures
Immutable Data Structures
 
The Case for Learned Index Structures
The Case for Learned Index StructuresThe Case for Learned Index Structures
The Case for Learned Index Structures
 
Spark and Spark Streaming
Spark and Spark StreamingSpark and Spark Streaming
Spark and Spark Streaming
 
第三届阿里中间件性能挑战赛冠军队伍答辩
第三届阿里中间件性能挑战赛冠军队伍答辩第三届阿里中间件性能挑战赛冠军队伍答辩
第三届阿里中间件性能挑战赛冠军队伍答辩
 
Data Streaming Algorithms
Data Streaming AlgorithmsData Streaming Algorithms
Data Streaming Algorithms
 
Golang 101
Golang 101Golang 101
Golang 101
 
Docker Container: isolation and security
Docker Container: isolation and securityDocker Container: isolation and security
Docker Container: isolation and security
 
Paxos and Raft Distributed Consensus Algorithm
Paxos and Raft Distributed Consensus AlgorithmPaxos and Raft Distributed Consensus Algorithm
Paxos and Raft Distributed Consensus Algorithm
 

Recently uploaded

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 

Recently uploaded (20)

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 

Functional Programming in Java 8

  • 2. Contents • Lambda • Stream • Parallelization • Asynchronization
  • 4. Higher-order Function ... is a function that does at least one of the following: • Takes one or more functions as arguments • Returns a function as its result Cache<String, String> cache = CacheBuilder.newBuilder().build(); String sql = "SQL_1"; String result = cache.get(sql, new Callable<String>() { @Override public String call() throws Exception { return "I am the syntax tree of " + sql; } }));
  • 5. What is Lambda Expression? Lambda is just a syntactic sugar, but it will change how you programing. Cache<String, String> cache = CacheBuilder.newBuilder().build(); String sql = "SQL_1"; String result = cache.get(sql, new Callable<String>() { @Override public String call() throws Exception { return "I am the syntax tree of " + sql; } })); String result = cache.get(sql, () -> "I am the syntax tree of " + sql);
  • 6.
  • 7. Closures • sql is passed to this Callable. How? Cache<String, String> cache = CacheBuilder.newBuilder().build(); String sql = "SQL_1"; String result = cache.get(sql, new Callable<String>() { @Override public String call() throws Exception { return "I am the syntax tree of " + sql; } })); String result = cache.get(sql, () -> "I am the syntax tree of " + sql);
  • 8. • How to pass a function along with its context as an argument? • (extend) How to implement a linked list with Closures? Objects are poor man's closures. Closures are poor man's objects. Closures <=> Objects
  • 9. Functional Interfaces • Interfaces with only one abstract method. • @FunctionalInterface public interface ActionListener { public void actionPerformed(ActionEvent event); }
  • 10. Logger + Lambda Logger logger = new Logger(); if (logger.isDebugEnabled()) { logger.debug("Look at this: " + expensiveOperation()); } Logger logger = new Logger(); logger.debug(() -> "Look at this: " + expensiveOperation()); function is first class object in Functional Programing
  • 12. Example • Given List<Artist> • Filter artists living in China public final class Album { private String name; private List<Track> tracks; private List<Artist> musicians; } public final class Artist { private String name; private List<Artist> members; private String nationality; } public final class Track { private final String name; private final int length; }
  • 13. Without streams... public List<Artist> artistsLivingInLondon() { List<Artist> results = new ArrayList<>(); for (Artist artist : artists) { if ("China".equals(artist.getNationality())) { results.add(artist); } } return results; }
  • 14. Example • Given List<Artist>, filter artists living in China • Given List<Artist>, return names of all artists public List<Artist> artistsLivingInChina() { return artists.stream() .filter(artist -> "China".equals(artist.getNationality())) .collect(Collectors.toList()); } public List<String> getNamesOfArtists_MethodReference() { return artists.stream() .map(Artist::getName) .collect(Collectors.toList()); }
  • 15. Basic Operations • map • filter • flatMap • collect • max/min
  • 16. Refactoring Set<String> findLongTracks(List<Album> albums) Find all long tracks (length >= 60) in a list of albums public final class Track { private final String name; private final int length; }
  • 17. Legacy Code public Set<String> findLongTracks(List<Album> albums) { Set<String> trackNames = new HashSet<>(); for(Album album : albums) { for (Track track : album.getTrackList()) { if (track.getLength() > 60) { String name = track.getName(); trackNames.add(name); } } } return trackNames; }
  • 18. Step 1 public Set<String> findLongTracks(List<Album> albums) { Set<String> trackNames = new HashSet<>(); albums.stream() .forEach(album -> { album.getTracks() .forEach(track -> { if (track.getLength() > 60) { String name = track.getName(); trackNames.add(name); } }); }); return trackNames; }
  • 20. Step 2 public Set<String> findLongTracks(List<Album> albums) { Set<String> trackNames = new HashSet<>(); albums.stream() .forEach(album -> { album.getTracks() .filter(track -> track.getLength() > 60) .map(track -> track.getName()) .forEach(name -> trackNames.add(name)); }); return trackNames; }
  • 22. Step 3 public Set<String> findLongTracks(List<Album> albums) { Set<String> trackNames = new HashSet<>(); albums.stream() .flatMap(album -> album.getTracks()) .filter(track -> track.getLength() > 60) .map(track -> track.getName()) .forEach(name -> trackNames.add(name)); return trackNames; }
  • 24. Step 4 public Set<String> findLongTracks(List<Album> albums) { return albums.stream() .flatMap(album -> album.getTracks()) .filter(track -> track.getLength() > 60) .map(track -> track.getName()) .collect(toSet()); }
  • 25. More Collectors • counting • reducing • partitioningBy • groupingBy • joining • maxBy • minBy ...
  • 26. public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) { return albums.collect(groupingBy(album -> album.getMainMusician(), counting())); } Downstream Collector public Map<Artist, Integer> numberOfAlbumsDumb(Stream<Album> albums) { Map<Artist, List<Album>> albumsByArtist = albums.collect(groupingBy(album -> album.getMainMusician())); Map<Artist, Integer> numberOfAlbums = new HashMap<>(); for(Entry<Artist, List<Album>> entry : albumsByArtist.entrySet()) { numberOfAlbums.put(entry.getKey(), entry.getValue().size()); } return numberOfAlbums; }
  • 28. stream.parallel() public Map<Integer, Double> parallelDiceRolls() { double fraction = 1.0 / N; return IntStream.range(0, N) .mapToObj(twoDiceThrows()) .collect(groupingBy(side -> side, summingDouble(n -> fraction))); } private static IntFunction<Integer> twoDiceThrows() { return i -> { ThreadLocalRandom random = ThreadLocalRandom.current(); int firstThrow = random.nextInt(1, 7); int secondThrow = random.nextInt(1, 7); return firstThrow + secondThrow; }; }
  • 29. stream.parallel() public Map<Integer, Double> parallelDiceRolls() { double fraction = 1.0 / N; return IntStream.range(0, N) .parallel() .mapToObj(twoDiceThrows()) .collect(groupingBy(side -> side, summingDouble(n -> fraction))); } private static IntFunction<Integer> twoDiceThrows() { return i -> { ThreadLocalRandom random = ThreadLocalRandom.current(); int firstThrow = random.nextInt(1, 7); int secondThrow = random.nextInt(1, 7); return firstThrow + secondThrow; }; }
  • 30. ForkJoinPool class Fibonacci extends RecursiveTask<Long> { final Long n; Fibonacci(Long n) { this.n = n; } @Override public Long compute() { if (n <= 1) return n; Fibonacci f1 = new Fibonacci(n - 1); f1.fork(); Fibonacci f2 = new Fibonacci(n - 2); return f2.compute() + f1.join(); } }
  • 31. ForkJoinPool • Design for compute-intensive tasks • Work stealing algorithm • No blocking
  • 33. Problem of Futurue • Call future.get() will block current thread
  • 34. public Album lookupByName(String albumName) { Future<Credentials> trackLogin = loginTo("track"); Future<Credentials> artistLogin = loginTo("artist"); try { Future<List<Track>> tracks = lookupTracks(albumName, trackLogin.get()); Future<List<Artist>> artists = lookupArtists(albumName, artistLogin.get()); return new Album(albumName, tracks.get(), artists.get()); } catch (InterruptedException | ExecutionException e) { throw new AlbumLookupException(e.getCause()); } }
  • 35. CompletableFuture public Album lookupByName(String albumName) { CompletableFuture<List<Artist>> artistLookup = loginTo("artist") .thenCompose(artistLogin -> lookupArtists(albumName, artistLogin)); CompletableFuture<List<Track>> trackLookup = loginTo("track") .thenCompose(trackLogin -> lookupTracks(albumName, trackLogin)); return trackLookup .thenCombine(artistLookup, (tracks, artists) -> new Album(albumName, tracks, artists)) .join(); }
  • 36. Another side... future.complete(artist); future.completeExceptionally(new AlbumLookupException("Cannot find " + name)); private CompletableFuture<List<Track>> lookupTracks(String albumName, Credentials credentials) { return CompletableFuture.supplyAsync(() -> { sleep(1000); return tracks; }, service); }
  • 37. RxJava Observable handles a stream of events
  • 38. A Kind Reminder • How to make everything functional? • Pure Function • Object • Loop • What is Curry? • What is Y-combinator? ..... Functional Programming in Java
  • 39. A Kind Reminder • The Magic Book - SICP