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
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
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
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
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
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