SlideShare a Scribd company logo
Java 8 :: Project Lambda
λ
Ivar Conradi Østhus
ico@finn.no

1 / 31
Java 8 - a few new (important) features
Lambda expressions
greater impact than generics in Java 1.5
Stream API
Default methods in interfaces
Compact Profiles
Nashorn JavaScript Engine
More annotations
Parallel Array Sorting
(new) Date & Time API
Concurrency Updates
.
.
.
Scheduled for March 2014
Complete list: http://openjdk.java.net/projects/jdk8/features

2 / 31
Warning:
a lot of code examples in this presentation!

3 / 31
Imperative style: for each element
Ls<nee>nmes=Ary.sit1 2 3 4 5 6;
itItgr ubr
rasaLs(, , , , , )

/1 odlo
/: l op
friti=0 i<nmessz(;i+ {
o(n
;
ubr.ie) +)
Sse.u.rnl()
ytmotpitni;
}
/2 ehne frlo
/: nacd o-op
frItgrn:nmes {
o(nee
ubr)
Sse.u.rnl()
ytmotpitnn;
}

4 / 31
Declarative style: for each element
Ls<nee>nmes=Ary.sit1 2 3 4 5 6;
itItgr ubr
rasaLs(, , , , , )
pbi itraeIeal<>{
ulc nefc trbeT
..
.
vi frahCnue< sprT ato)
od oEc(osmr? ue > cin;
..
.
}

With anonymous inner class:
nmesfrahnwCnue<nee>){
ubr.oEc(e osmrItgr(
pbi vi acp(nee nme){
ulc od cetItgr ubr
Sse.u.rnl(ubr;
ytmotpitnnme)
}
};
)

With lambda expression:
nmesfrah(nee n - Sse.u.rnl();
ubr.oEc(Itgr ) > ytmotpitnn)

5 / 31
What is a functional interfaces?
@ucinlnefc
FntoaItrae
pbi itraePeiaeT {
ulc nefc rdct<>
boents( t;
ola etT )
}
one abstract unimplemented method
optional @FunctionalInterface annotation
already a lot of functional interfaces in java
Java API will be full of functional interfaces

6 / 31
Functional interfaces added in Java 8
Cnue<>
osmrT
/tksa iptTadprom a oeaino i.
/ae n nu
n efrs n prto n t
Sple<>
upirT
/akn o fcoy wl rtr anwo eitn isac.
/ id f atr, il eun
e r xsig ntne
PeiaeT
rdct<>
/Cek i agmn Tstsisarqieet
/hcs f ruet
aife
eurmn.
Fnto<,R
ucinT >
/Tasoma agmn fo tp Tt tp R
/rnfr n ruet rm ye
o ye .

7 / 31
Methods taking a functional interface will accept:
an anonymous inner class
a lambda expression
a method reference

8 / 31
Lambda: types
Single expression
(nee i - i*2
Itgr ) >
;

Statement block
(n x ity - {rtr x+y }
it , n ) >
eun
;

/mlil lnso cd
/utpe ie f oe
(n n - {
it ) >
itvle=n2
n au
*;
rtr vle
eun au;
}
;

9 / 31
Lambda: type inference
(nee i - i*2
Itgr ) >
;
()- i*2
i >
;
i- i2
> *;

/Mlil prm
/utpe aas
(n x ity - x+y
it , n ) >
(,y - x+y
x ) >

10 / 31
Reuse lambdas
Ls<nee>nmes=Ary.sit1 2 3 4 5 6;
itItgr ubr
rasaLs(, , , , , )

Function
pbi sai Cnue<nee>cnue( {
ulc ttc osmrItgr osmr)
rtr (nee n - Sse.u.rnl()
eun Itgr ) > ytmotpitnn;
}
nmesfrahcnue()
ubr.oEc(osmr);

Variable
pbi Cnue<nee>cnue =(nee n - Sse.u.rnl()
ulc osmrItgr osmr
Itgr ) > ytmotpitnn;
nmesfrahcnue)
ubr.oEc(osmr;

11 / 31
Method reference
Ls<nee>nmes=Ary.sit1 2 3 4 5 6;
itItgr ubr
rasaLs(, , , , , )

/Lmd
/aba
nmesfrahn- Sse.u.rnl();
ubr.oEc( > ytmotpitnn)
/Mto rfrne
/ehd eeec
nmesfrahSse.u:pitn;
ubr.oEc(ytmot:rnl)

12 / 31
Lambda summary
(n x ity - {rtr x+y }
it , n ) >
eun
;
(,y - x+y
x ) >
x- x+x
>
( - x
) >
enables better libraries
uses lexical scoping
requires effectively final

13 / 31
The Java Stream API

14 / 31
Task: Double and sum all even numbers
Ls<nee>nmes=Ary.sit1 2 3 4 5 6;
itItgr ubr
rasaLs(, , , , , )

Imperative solution
itsmfobeEeNr =0
n uODuldvnbs
;
fritnme :nmes {
o(n ubr
ubr)
i(ubr%2= 0 {
fnme
= )
smfobeEeNr + nme *2
uODuldvnbs = ubr
;
}
}

Declarative solution
itsm=nmessra(
n u
ubr.tem)
.itrn- n%2= 0
fle( >
= )
.aTItn- n*2
mpon( >
)
.u(;
sm)

15 / 31
The Java Stream API
Integration of lambda expressions with the Collection API's
An abstraction for specifying aggregate computation on data set
Streams are like iterators, yield elements for processing
Streams can be finite and infinite
Intention: replace loops for aggregate operations

Streams gives us:
more readable code
more composable operations
parallizable

Think of Stream pipelines as builders:
have stream source
add many intermediate operations
execute pipeline ONCE
Side note: Pipes in linux
ctidxhm |t "AZ""az"|ge lmd |sr
a ne.tl
r [-] [-]
rp aba
ot

16 / 31
Source
collections, arrays, generator functions, IO
can be finite or infinite
do NOT modify the source during query

Intermediate operations
filter, map, mapToInt, flatMap, sorted, distinct, limit...
stateless or statefull
lazy -- returns new streams
lambdas used to transform or drop values

Terminal operation
Aggregation: toArray, toList, reduce, sum, min, max, count, anyMatch, allMatch
Iteration: forEach
Searching: findFirst, findAny
produces a result / side-effect

17 / 31
Stream: sources
Collections
Ls<esn pros=nwAryit>)
itPro> esn
e raLs<(;
Sra<esn proSra =prossra(;
temPro> esntem
esn.tem)

IO
Sra<tig lnSra =bfeeRae.ie(;
temSrn> ietem
ufrdedrlns)

Stream factories
/rne
/ag
Ittemnmes=Ittemrne0 1)
nSra ubr
nSra.ag(, 0;
/rno nmes
/adm ubr
DulSra rnoDuls=nwRno(.obe(;
obetem admobe
e adm)duls)
IttemrnoIt =nwRno(.ns0 1)
nSra admns
e adm)it(, 0;
(Primitive streams are included for performance reasons)
18 / 31
Stream: intermediate operations
returns a Stream, not elements
they are lazy

filter
Sra<esn sra =prossra(.itrp- pgtg( >1)
temPro> tem
esn.tem)fle( > .eAe)
7;

map
Sra<tig sra =prossra(.a(esn:eNm)
temSrn> tem
esn.tem)mpPro:gtae;

mapToInt
Ittemsra3=prossra(.aTItPro:gtg)
nSra tem
esn.tem)mpon(esn:eAe;

19 / 31
Stream: statefull intermediate operations
harder to parallelize
Examples: limit, substream, sorted, distinct
Sra<esn sreSra =prossra(
temPro> otdtem
esn.tem)
.itrp- pgtg( >1)
fle( > .eAe)
7
.otd(1 p)- p.eAe)-p.eAe);
sre(p, 2 > 1gtg(
2gtg()

20 / 31
Stream: terminal operations
return non-stream elements
eager: force evaluation of the stream
Task: Find the average age in Sandnes
OtoaDul aeae=prossra(
pinlobe vrg
esn.tem)
.itrp- pgtiy)eul(Snns)
fle( > .eCt(.qas"ade")
.aTItp- pgtg()
mpon( > .eAe)
.vrg(;
aeae)
(How would an imperative solution look like?)

21 / 31
Imperative solution
Task: Find the average age in Sandnes
itsm=0
n u
;
itcut=0
n on
;
frPro pro :pros{
o(esn esn
esn)
i(esngtiy)eul(Snns) {
fpro.eCt(.qas"ade")
sm+ pro.eAe)
u = esngtg(;
cut+;
on +
}
}
dul aeaegISnns=(obesm/cut
obe vrgAenade
dul)u
on;
The Stream solution:
OtoaDul aeae=prossra(
pinlobe vrg
esn.tem)
.itrp- pgtiy)eul(Snns)
fle( > .eCt(.qas"ade")
.aTItp- pgtg()
mpon( > .eAe)
.vrg(;
aeae)

22 / 31
Stream: Collector
aggregate values in to a container
many predefined collectors in j v . t l s r a . o l c o s
aaui.temCletr
counting
averaging/summarizing/sum/min
toList/toMap/toSet
reducing
groupingBy
mapping
Collectors.toSet()
StSrn>nms=prossra(
e<tig ae
esn.tem)
.a(esn:eNm)
mpPro:gtae
.olc(oe()
clettSt);
Result:
[vrØtu,Dnl Dc,OaHne,Kr Nran SleHne,
Ia shs oad uk l asn ai omn, ij asn
KetnLlerr
nre ilbo]

23 / 31
Stream: Collector - groupingBy
Collectors.groupingBy: age
MpItgr Ls<esn>prosyg =
a<nee, itPro> esnBAe
prossra(.olc(ruigyPro:gtg);
esn.tem)cletgopnB(esn:eAe)
groupingBy age, and only get their names
MpItgr Ls<tig>nmBAe=
a<nee, itSrn> aeyg
prossra(
esn.tem)
.olc(ruigyPro:gtg,mpigPro:gtae tLs())
cletgopnB(esn:eAe apn(esn:eNm, oit));

24 / 31
Stream the contents of a CSV file
Map persons in a CSV to a list of persons and return the 50 first adults.
nm,ae ct,cuty
ae g, iy onr
Ia Øtu,2,Ol,Nra
vr shs 8 so owy
VsaahnAad 4,Myldtua,Ida
iwnta nn, 3 aiauhri ni
Mgu Crsn 2,Tnbr,Nra
ans ale, 2 øseg owy
.
.
Ipttemi =nwFlIpttemnwFl(proscv);
nuSra s
e ienuSra(e ie"esn.s")
BfeeRae b =nwBfeeRae(e Ipttemedri);
ufrdedr r
e ufrdedrnw nuSraRae(s)
Ls<esn pros=b.ie(
itPro> esn
rlns)
.usra()
sbtem1
.a(oesn
mptPro)
.itriAut
fle(sdl)
.ii(0
lmt5)
.olc(oit);
clettLs()

/lmds
/aba
pbi sai Fnto<tig Pro>tPro =(ie - {
ulc ttc ucinSrn, esn oesn
ln) >
Srn[ p=ln.pi(,";
tig]
ieslt" )
rtr nwPro([] Itgrpren([],p2,p3)
eun e esnp0, nee.asItp1) [] [];
}
;
pbi sai PeiaePro>iAut=p- pgtg( >1;
ulc ttc rdct<esn sdl
> .eAe)
7
25 / 31
Parallel Streams
/Sqeta
/eunil
OtoaDul aeae=prossra(
pinlobe vrg
esn.tem)
.itrp- pgtiy)eul(Snns)
fle( > .eCt(.qas"ade")
.aTItp- pgtg()
mpon( > .eAe)
.vrg(;
aeae)
/Prle
/aall
OtoaDul aeae=prosprleSra(
pinlobe vrg
esn.aalltem)
.itrp- pgtiy)eul(Snns)
fle( > .eCt(.qas"ade")
.aTItp- pgtg()
mpon( > .eAe)
.vrg(;
aeae)

26 / 31
Parallel Streams: visual model

(Source: https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7942)

27 / 31
Streams: performance
N=sz o suc
ie f ore
Q=cs preeettruhteppln
ot e-lmn hog h ieie
N*Q~ cs o ppln
= ot f ieie
Larger N * Q → higher chance of good parallel performance
Genererally it is easier to know N
For small data sets → sequential usually wins
Complex pipelines are harder to reason about
What are the stream characteristics?
Do not assume parallel is always faster!

MEASURE!!!

28 / 31
Interface: default methods
Java Collections Framework
designed fifteen years ago
without a functional orientation
do not have a method forEach, stream, ..
Until now adding new methods to an interface has been impossible without forcing
modification to existing classes
Solution: default methods in interfaces
(also called virtual extension methods or defender methods)
A clever way to enhance existing interfaces with new methods
itraeIeao {
nefc trtr
/ eitn mto dcaain
/ xsig ehd elrtos
dfutvi si( {
eal od kp)
i (aNx()nx(;
f hset) et)
}
}

29 / 31
Stream API: summary
Sources:
Collections, Generator functions, IO
Intermediate functions:
filter, map, sorted, limit
lazy
Terminal operations:
sum, max, min, collect, groupingBy
eager

30 / 31
Books:

Functional Programming in Java
Vankat Subramaniam

Java 8 Lambdas in Action
Raoul-Gabriel Urma, Mario Fusco, and Alan
Mycroft

Presentations:
https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7942
https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7504
http://www.slideshare.net/jaxlondon2012/lambda-a-peek-under-the-hood-brian-goetz

Videos:
http://parleys.com/channel/5243df06e4b0d1fb3c78fe31/presentations?
sort=date&state=public

31 / 31

More Related Content

PDF
Java 8 Lambda Expressions
PDF
Java Class Design
PPTX
What is new in Java 8
PDF
JavaOne 2016 - Learn Lambda and functional programming
PDF
Functional Programming in Java 8 - Exploiting Lambdas
PDF
PDF
Functional Algebra: Monoids Applied
PPTX
Java Generics
Java 8 Lambda Expressions
Java Class Design
What is new in Java 8
JavaOne 2016 - Learn Lambda and functional programming
Functional Programming in Java 8 - Exploiting Lambdas
Functional Algebra: Monoids Applied
Java Generics

What's hot (20)

PDF
Java Class Design
PDF
Java 8 Stream API. A different way to process collections.
PDF
ScalaFlavor4J
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
PDF
Why Haskell
PDF
The... Wonderful? World of Lambdas
PDF
Advanced Debugging Using Java Bytecodes
PDF
Lambda and Stream Master class - part 1
PDF
Lambda? You Keep Using that Letter
PDF
Java Generics - by Example
PPTX
Functional programming seminar (haskell)
PDF
Java 8 Lambda Built-in Functional Interfaces
PDF
C# features through examples
PDF
Refactoring to Immutability
PPT
Collection Core Concept
PDF
Collectors in the Wild
PDF
If You Think You Can Stay Away from Functional Programming, You Are Wrong
PDF
Lambdas and Streams Master Class Part 2
PDF
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
PDF
Procedural Programming: It’s Back? It Never Went Away
Java Class Design
Java 8 Stream API. A different way to process collections.
ScalaFlavor4J
Design Patterns - Compiler Case Study - Hands-on Examples
Why Haskell
The... Wonderful? World of Lambdas
Advanced Debugging Using Java Bytecodes
Lambda and Stream Master class - part 1
Lambda? You Keep Using that Letter
Java Generics - by Example
Functional programming seminar (haskell)
Java 8 Lambda Built-in Functional Interfaces
C# features through examples
Refactoring to Immutability
Collection Core Concept
Collectors in the Wild
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Lambdas and Streams Master Class Part 2
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
Procedural Programming: It’s Back? It Never Went Away
Ad

Viewers also liked (14)

PPTX
Java 8 presentation
PPTX
New Features in JDK 8
PPTX
55 New Features in Java SE 8
PPTX
Lambda Expressions in Java 8
PDF
PPTX
Java SE 8 - New Features
PPTX
Java 8 - Features Overview
PDF
Java8 features
PPTX
Java 8 Features
PDF
PPTX
OCP Java (OCPJP) 8 Exam Quick Reference Card
PDF
Cracking OCA and OCP Java 8 Exams
PDF
Sailing with Java 8 Streams
PDF
Functional Thinking - Programming with Lambdas in Java 8
Java 8 presentation
New Features in JDK 8
55 New Features in Java SE 8
Lambda Expressions in Java 8
Java SE 8 - New Features
Java 8 - Features Overview
Java8 features
Java 8 Features
OCP Java (OCPJP) 8 Exam Quick Reference Card
Cracking OCA and OCP Java 8 Exams
Sailing with Java 8 Streams
Functional Thinking - Programming with Lambdas in Java 8
Ad

Similar to Java 8 - project lambda (20)

PDF
Flow of events during Media Player creation in Android
PDF
Ff to-fp
PDF
Clojurescript up and running
PDF
JavaFX, because you're worth it
PDF
Lambdas myths-and-mistakes
PDF
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
PDF
OOP in Rust
PDF
nescala 2013
PDF
JavaScript Design Patterns
PDF
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
PDF
Architecting Android Apps: Marko Gargenta
PDF
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
PDF
Operation Flow @ ChicagoRoboto
PDF
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
PDF
SecureSocial - Authentication for Play Framework
PPTX
Joker 2015 - Валеев Тагир - Что же мы измеряем?
PDF
Nginx Scripting - Extending Nginx Functionalities with Lua
PDF
Devinsampa nginx-scripting
PDF
Cassandra EU - State of CQL
PDF
C* Summit EU 2013: The State of CQL
Flow of events during Media Player creation in Android
Ff to-fp
Clojurescript up and running
JavaFX, because you're worth it
Lambdas myths-and-mistakes
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
OOP in Rust
nescala 2013
JavaScript Design Patterns
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
Architecting Android Apps: Marko Gargenta
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
Operation Flow @ ChicagoRoboto
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
SecureSocial - Authentication for Play Framework
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Nginx Scripting - Extending Nginx Functionalities with Lua
Devinsampa nginx-scripting
Cassandra EU - State of CQL
C* Summit EU 2013: The State of CQL

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MIND Revenue Release Quarter 2 2025 Press Release
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
“AI and Expert System Decision Support & Business Intelligence Systems”
A comparative analysis of optical character recognition models for extracting...
20250228 LYD VKU AI Blended-Learning.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
Electronic commerce courselecture one. Pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectroscopy.pptx food analysis technology
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The AUB Centre for AI in Media Proposal.docx

Java 8 - project lambda

  • 1. Java 8 :: Project Lambda λ Ivar Conradi Østhus [email protected] 1 / 31
  • 2. Java 8 - a few new (important) features Lambda expressions greater impact than generics in Java 1.5 Stream API Default methods in interfaces Compact Profiles Nashorn JavaScript Engine More annotations Parallel Array Sorting (new) Date & Time API Concurrency Updates . . . Scheduled for March 2014 Complete list: http://openjdk.java.net/projects/jdk8/features 2 / 31
  • 3. Warning: a lot of code examples in this presentation! 3 / 31
  • 4. Imperative style: for each element Ls<nee>nmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , ) /1 odlo /: l op friti=0 i<nmessz(;i+ { o(n ; ubr.ie) +) Sse.u.rnl() ytmotpitni; } /2 ehne frlo /: nacd o-op frItgrn:nmes { o(nee ubr) Sse.u.rnl() ytmotpitnn; } 4 / 31
  • 5. Declarative style: for each element Ls<nee>nmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , ) pbi itraeIeal<>{ ulc nefc trbeT .. . vi frahCnue< sprT ato) od oEc(osmr? ue > cin; .. . } With anonymous inner class: nmesfrahnwCnue<nee>){ ubr.oEc(e osmrItgr( pbi vi acp(nee nme){ ulc od cetItgr ubr Sse.u.rnl(ubr; ytmotpitnnme) } }; ) With lambda expression: nmesfrah(nee n - Sse.u.rnl(); ubr.oEc(Itgr ) > ytmotpitnn) 5 / 31
  • 6. What is a functional interfaces? @ucinlnefc FntoaItrae pbi itraePeiaeT { ulc nefc rdct<> boents( t; ola etT ) } one abstract unimplemented method optional @FunctionalInterface annotation already a lot of functional interfaces in java Java API will be full of functional interfaces 6 / 31
  • 7. Functional interfaces added in Java 8 Cnue<> osmrT /tksa iptTadprom a oeaino i. /ae n nu n efrs n prto n t Sple<> upirT /akn o fcoy wl rtr anwo eitn isac. / id f atr, il eun e r xsig ntne PeiaeT rdct<> /Cek i agmn Tstsisarqieet /hcs f ruet aife eurmn. Fnto<,R ucinT > /Tasoma agmn fo tp Tt tp R /rnfr n ruet rm ye o ye . 7 / 31
  • 8. Methods taking a functional interface will accept: an anonymous inner class a lambda expression a method reference 8 / 31
  • 9. Lambda: types Single expression (nee i - i*2 Itgr ) > ; Statement block (n x ity - {rtr x+y } it , n ) > eun ; /mlil lnso cd /utpe ie f oe (n n - { it ) > itvle=n2 n au *; rtr vle eun au; } ; 9 / 31
  • 10. Lambda: type inference (nee i - i*2 Itgr ) > ; ()- i*2 i > ; i- i2 > *; /Mlil prm /utpe aas (n x ity - x+y it , n ) > (,y - x+y x ) > 10 / 31
  • 11. Reuse lambdas Ls<nee>nmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , ) Function pbi sai Cnue<nee>cnue( { ulc ttc osmrItgr osmr) rtr (nee n - Sse.u.rnl() eun Itgr ) > ytmotpitnn; } nmesfrahcnue() ubr.oEc(osmr); Variable pbi Cnue<nee>cnue =(nee n - Sse.u.rnl() ulc osmrItgr osmr Itgr ) > ytmotpitnn; nmesfrahcnue) ubr.oEc(osmr; 11 / 31
  • 12. Method reference Ls<nee>nmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , ) /Lmd /aba nmesfrahn- Sse.u.rnl(); ubr.oEc( > ytmotpitnn) /Mto rfrne /ehd eeec nmesfrahSse.u:pitn; ubr.oEc(ytmot:rnl) 12 / 31
  • 13. Lambda summary (n x ity - {rtr x+y } it , n ) > eun ; (,y - x+y x ) > x- x+x > ( - x ) > enables better libraries uses lexical scoping requires effectively final 13 / 31
  • 14. The Java Stream API 14 / 31
  • 15. Task: Double and sum all even numbers Ls<nee>nmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , ) Imperative solution itsmfobeEeNr =0 n uODuldvnbs ; fritnme :nmes { o(n ubr ubr) i(ubr%2= 0 { fnme = ) smfobeEeNr + nme *2 uODuldvnbs = ubr ; } } Declarative solution itsm=nmessra( n u ubr.tem) .itrn- n%2= 0 fle( > = ) .aTItn- n*2 mpon( > ) .u(; sm) 15 / 31
  • 16. The Java Stream API Integration of lambda expressions with the Collection API's An abstraction for specifying aggregate computation on data set Streams are like iterators, yield elements for processing Streams can be finite and infinite Intention: replace loops for aggregate operations Streams gives us: more readable code more composable operations parallizable Think of Stream pipelines as builders: have stream source add many intermediate operations execute pipeline ONCE Side note: Pipes in linux ctidxhm |t "AZ""az"|ge lmd |sr a ne.tl r [-] [-] rp aba ot 16 / 31
  • 17. Source collections, arrays, generator functions, IO can be finite or infinite do NOT modify the source during query Intermediate operations filter, map, mapToInt, flatMap, sorted, distinct, limit... stateless or statefull lazy -- returns new streams lambdas used to transform or drop values Terminal operation Aggregation: toArray, toList, reduce, sum, min, max, count, anyMatch, allMatch Iteration: forEach Searching: findFirst, findAny produces a result / side-effect 17 / 31
  • 18. Stream: sources Collections Ls<esn pros=nwAryit>) itPro> esn e raLs<(; Sra<esn proSra =prossra(; temPro> esntem esn.tem) IO Sra<tig lnSra =bfeeRae.ie(; temSrn> ietem ufrdedrlns) Stream factories /rne /ag Ittemnmes=Ittemrne0 1) nSra ubr nSra.ag(, 0; /rno nmes /adm ubr DulSra rnoDuls=nwRno(.obe(; obetem admobe e adm)duls) IttemrnoIt =nwRno(.ns0 1) nSra admns e adm)it(, 0; (Primitive streams are included for performance reasons) 18 / 31
  • 19. Stream: intermediate operations returns a Stream, not elements they are lazy filter Sra<esn sra =prossra(.itrp- pgtg( >1) temPro> tem esn.tem)fle( > .eAe) 7; map Sra<tig sra =prossra(.a(esn:eNm) temSrn> tem esn.tem)mpPro:gtae; mapToInt Ittemsra3=prossra(.aTItPro:gtg) nSra tem esn.tem)mpon(esn:eAe; 19 / 31
  • 20. Stream: statefull intermediate operations harder to parallelize Examples: limit, substream, sorted, distinct Sra<esn sreSra =prossra( temPro> otdtem esn.tem) .itrp- pgtg( >1) fle( > .eAe) 7 .otd(1 p)- p.eAe)-p.eAe); sre(p, 2 > 1gtg( 2gtg() 20 / 31
  • 21. Stream: terminal operations return non-stream elements eager: force evaluation of the stream Task: Find the average age in Sandnes OtoaDul aeae=prossra( pinlobe vrg esn.tem) .itrp- pgtiy)eul(Snns) fle( > .eCt(.qas"ade") .aTItp- pgtg() mpon( > .eAe) .vrg(; aeae) (How would an imperative solution look like?) 21 / 31
  • 22. Imperative solution Task: Find the average age in Sandnes itsm=0 n u ; itcut=0 n on ; frPro pro :pros{ o(esn esn esn) i(esngtiy)eul(Snns) { fpro.eCt(.qas"ade") sm+ pro.eAe) u = esngtg(; cut+; on + } } dul aeaegISnns=(obesm/cut obe vrgAenade dul)u on; The Stream solution: OtoaDul aeae=prossra( pinlobe vrg esn.tem) .itrp- pgtiy)eul(Snns) fle( > .eCt(.qas"ade") .aTItp- pgtg() mpon( > .eAe) .vrg(; aeae) 22 / 31
  • 23. Stream: Collector aggregate values in to a container many predefined collectors in j v . t l s r a . o l c o s aaui.temCletr counting averaging/summarizing/sum/min toList/toMap/toSet reducing groupingBy mapping Collectors.toSet() StSrn>nms=prossra( e<tig ae esn.tem) .a(esn:eNm) mpPro:gtae .olc(oe() clettSt); Result: [vrØtu,Dnl Dc,OaHne,Kr Nran SleHne, Ia shs oad uk l asn ai omn, ij asn KetnLlerr nre ilbo] 23 / 31
  • 24. Stream: Collector - groupingBy Collectors.groupingBy: age MpItgr Ls<esn>prosyg = a<nee, itPro> esnBAe prossra(.olc(ruigyPro:gtg); esn.tem)cletgopnB(esn:eAe) groupingBy age, and only get their names MpItgr Ls<tig>nmBAe= a<nee, itSrn> aeyg prossra( esn.tem) .olc(ruigyPro:gtg,mpigPro:gtae tLs()) cletgopnB(esn:eAe apn(esn:eNm, oit)); 24 / 31
  • 25. Stream the contents of a CSV file Map persons in a CSV to a list of persons and return the 50 first adults. nm,ae ct,cuty ae g, iy onr Ia Øtu,2,Ol,Nra vr shs 8 so owy VsaahnAad 4,Myldtua,Ida iwnta nn, 3 aiauhri ni Mgu Crsn 2,Tnbr,Nra ans ale, 2 øseg owy . . Ipttemi =nwFlIpttemnwFl(proscv); nuSra s e ienuSra(e ie"esn.s") BfeeRae b =nwBfeeRae(e Ipttemedri); ufrdedr r e ufrdedrnw nuSraRae(s) Ls<esn pros=b.ie( itPro> esn rlns) .usra() sbtem1 .a(oesn mptPro) .itriAut fle(sdl) .ii(0 lmt5) .olc(oit); clettLs() /lmds /aba pbi sai Fnto<tig Pro>tPro =(ie - { ulc ttc ucinSrn, esn oesn ln) > Srn[ p=ln.pi(,"; tig] ieslt" ) rtr nwPro([] Itgrpren([],p2,p3) eun e esnp0, nee.asItp1) [] []; } ; pbi sai PeiaePro>iAut=p- pgtg( >1; ulc ttc rdct<esn sdl > .eAe) 7 25 / 31
  • 26. Parallel Streams /Sqeta /eunil OtoaDul aeae=prossra( pinlobe vrg esn.tem) .itrp- pgtiy)eul(Snns) fle( > .eCt(.qas"ade") .aTItp- pgtg() mpon( > .eAe) .vrg(; aeae) /Prle /aall OtoaDul aeae=prosprleSra( pinlobe vrg esn.aalltem) .itrp- pgtiy)eul(Snns) fle( > .eCt(.qas"ade") .aTItp- pgtg() mpon( > .eAe) .vrg(; aeae) 26 / 31
  • 27. Parallel Streams: visual model (Source: https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7942) 27 / 31
  • 28. Streams: performance N=sz o suc ie f ore Q=cs preeettruhteppln ot e-lmn hog h ieie N*Q~ cs o ppln = ot f ieie Larger N * Q → higher chance of good parallel performance Genererally it is easier to know N For small data sets → sequential usually wins Complex pipelines are harder to reason about What are the stream characteristics? Do not assume parallel is always faster! MEASURE!!! 28 / 31
  • 29. Interface: default methods Java Collections Framework designed fifteen years ago without a functional orientation do not have a method forEach, stream, .. Until now adding new methods to an interface has been impossible without forcing modification to existing classes Solution: default methods in interfaces (also called virtual extension methods or defender methods) A clever way to enhance existing interfaces with new methods itraeIeao { nefc trtr / eitn mto dcaain / xsig ehd elrtos dfutvi si( { eal od kp) i (aNx()nx(; f hset) et) } } 29 / 31
  • 30. Stream API: summary Sources: Collections, Generator functions, IO Intermediate functions: filter, map, sorted, limit lazy Terminal operations: sum, max, min, collect, groupingBy eager 30 / 31
  • 31. Books: Functional Programming in Java Vankat Subramaniam Java 8 Lambdas in Action Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft Presentations: https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7942 https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7504 http://www.slideshare.net/jaxlondon2012/lambda-a-peek-under-the-hood-brian-goetz Videos: http://parleys.com/channel/5243df06e4b0d1fb3c78fe31/presentations? sort=date&state=public 31 / 31