Java 8 - project lambda

Click here to load reader

  • date post

    10-May-2015
  • Category

    Technology

  • view

    740
  • download

    4

Embed Size (px)

description

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

Transcript of Java 8 - project lambda

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/features2 / 31 3. Warning: a lot of code examples in this presentation!3 / 31 4. Imperative style: for each element Lsnmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , )/1 odlo /: l op friti=0 inmes=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){ 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 interfaces6 / 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 /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 reference8 / 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 Lsnmes=Ary.sit1 2 3 4 5 6; itItgr ubr rasaLs(, , , , , )Function pbi sai Cnuecnue( { ulc ttc osmrItgr osmr) rtr (nee n - Sse.u.rnl() eun Itgr ) > ytmotpitnn; } nmesfrahcnue() ubr.oEc(osmr);Variable pbi Cnuecnue =(nee n - Sse.u.rnl() ulc osmrItgr osmr Itgr ) > ytmotpitnn; nmesfrahcnue) ubr.oEc(osmr;11 / 31 12. Method reference Lsnmes=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 final13 / 31 14. The Java Stream API14 / 31 15. Task: Double and sum all even numbers Lsnmes=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 operationsStreams gives us: more readable code more composable operations parallizableThink 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 ot16 / 31 17. Source collections, arrays, generator functions, IO can be finite or infinite do NOT modify the source during queryIntermediate operations filter, map, mapToInt, flatMap, sorted, distinct, limit... stateless or statefull lazy -- returns new streams lambdas used to transform or drop valuesTerminal operation Aggregation: toArray, toList, reduce, sum, min, max, count, anyMatch, allMatch Iteration: forEach Searching: findFirst, findAny produces a result / side-effect17 / 31 18. Stream: sources Collections Ls) itPro> esn e raLs tem esn.tem)fle( > .eAe) 7;map Sra 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 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( eprosyg = a esnBAe prossra(.olc(ruigyPro:gtg); esn.tem)cletgopnB(esn:eAe) groupingBy age, and only get their names MpItgr LsnmBAe= a 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 rlns) .usra() sbtem1 .a(oesn mptPro) .itriAut fle(sdl) .ii(0 lmt5) .olc(oit); clettLs()/lmds /aba pbi sai FntotPro =(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 .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 eager30 / 31 31. Books:Functional Programming in Java Vankat SubramaniamJava 8 Lambdas in Action Raoul-Gabriel Urma, Mario Fusco, and Alan MycroftPresentations: 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-goetzVideos: http://parleys.com/channel/5243df06e4b0d1fb3c78fe31/presentations? sort=date&state=public31 / 31