Java 8 - project lambda

1,904 views

Published on

Short presentation of lambdas and the Stream API coming in java 8. For more in depth details see my blog: http://ivarconr.wordpress.com

Published in: Technology, News & Politics
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,904
On SlideShare
0
From Embeds
0
Number of Embeds
1,107
Actions
Shares
0
Downloads
14
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Java 8 - project lambda

  1. 1. Java 8 :: Project Lambda λ Ivar Conradi Østhus ico@finn.no 1 / 31
  2. 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. 3. Warning: a lot of code examples in this presentation! 3 / 31
  4. 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. 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. 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. 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. 8. Methods taking a functional interface will accept: an anonymous inner class a lambda expression a method reference 8 / 31
  9. 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. 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. 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. 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. 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. 14. The Java Stream API 14 / 31
  15. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 27. Parallel Streams: visual model (Source: https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7942) 27 / 31
  28. 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. 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. 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. 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

×