SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1José Paumard
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)Bikram Thapa
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
C# features through examples
C# features through examplesC# features through examples
C# features through examplesZayen Chagra
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the WildJosé Paumard
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
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
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions Ganesh Samarthyam
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 

Mais procurados (20)

Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
ScalaFlavor4J
ScalaFlavor4JScalaFlavor4J
ScalaFlavor4J
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
C# features through examples
C# features through examplesC# features through examples
C# features through examples
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
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
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 

Destaque

Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New FeaturesNaveen Hegde
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 

Destaque (14)

Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Java8
Java8Java8
Java8
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Java8
Java8Java8
Java8
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 

Semelhante a Java 8 - project lambda

Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidSomenath Mukhopadhyay
 
Clojurescript up and running
Clojurescript up and runningClojurescript up and running
Clojurescript up and runningTimo Sulg
 
Lambdas myths-and-mistakes
Lambdas myths-and-mistakesLambdas myths-and-mistakes
Lambdas myths-and-mistakesRichardWarburton
 
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)
Lambda Expressions: Myths and Mistakes - Richard Warburton (jClarity)jaxLondonConference
 
nescala 2013
nescala 2013nescala 2013
nescala 2013Hung Lin
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design PatternsDerek Brown
 
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...
How to create a 3.2 billion dollar business in 20 minutes: combining AngularJ...Ari Lerner
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargentajaxconf
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best PracticesJohannes Hoppe
 
Operation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRobotoOperation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRobotoSeyed Jafari
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
SecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play FrameworkSecureSocial - Authentication for Play Framework
SecureSocial - Authentication for Play Frameworkjaliss
 
A Backbone.js Tutorial for the Impatient - Part 1
A Backbone.js Tutorial for the Impatient - Part 1A Backbone.js Tutorial for the Impatient - Part 1
A Backbone.js Tutorial for the Impatient - Part 1jsalonen Salonen
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?tvaleev
 
Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaTony Fabeen
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scriptingTony Fabeen
 
Cassandra EU - State of CQL
Cassandra EU - State of CQLCassandra EU - State of CQL
Cassandra EU - State of CQLpcmanus
 

Semelhante a Java 8 - project lambda (20)

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

Último

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Java 8 - project lambda

  • 1. Java 8 :: Project Lambda λ Ivar Conradi Østhus ico@finn.no 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