eclipse collec+ons and java 8 lambdas · • java.util.collections provides methods for sort(),...
TRANSCRIPT
![Page 1: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/1.jpg)
EclipseCollec+onsandJava8Lambdas
MiniCodeKataBasicIdeas,BasicImplementa+onsMarch2016
Copyright©2016GoldmanSachs.Allrightsreserved.
![Page 2: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/2.jpg)
INTRO
WhatisEclipseCollec+ons?
• AsupplementorreplacementfortheJavaCollecFonsFramework(JCF).• DevelopedoriginallyatGoldmanSachs.• "Inspiredby"SmalltalkCollecFonprotocol.
2
WhatisaCodeKata?
• AprogrammingexercisewhichhelpshoneyourskillsthroughpracFce.• Thisoneissetupasaseriesofunittestswhichfail.• Yourtaskistomakethempass,usingEclipseCollecFons–
IhearandIforget.IseeandIremember.IdoandIunderstand.
-Confucius
EclipseCollec+onsMiniCodeKata
• Newconceptsareintroducedintheslides• CodingexercisesareattheendofeachsecFon.
![Page 3: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/3.jpg)
ITERATIONPATTERNS
3
![Page 4: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/4.jpg)
ITERATIONP
ATTERNS
Sort
• WhatisaniteraFonpaWern?• Sortisoneexample.• Wewanttosortalistofpeoplebylastname,firstname.• WhichmethodintheJCFcanweuse?
Domain
Personjohn=newPerson("John","Smith");Personjane=newPerson("Jane","Smith");Personz=newPerson("Z.","Jones");List<Person>people=newArrayList<Person>();people.add(john);people.add(jane);people.add(z);
4
![Page 5: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/5.jpg)
ITERATIONP
ATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecifiedcomparator.Allelementsinthelistmustbemutuallycomparable.
Anonymousinnerclasssyntax
Collections.sort(people,newComparator<Person>(){publicintcompare(Persono1,Persono2){intlastName=o1.getLastName().compareTo(o2.getLastName());if(lastName!=0){returnlastName;}returno1.getFirstName().compareTo(o2.getFirstName());}});
5
![Page 6: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/6.jpg)
ITERATIONP
ATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecifiedcomparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
6
![Page 7: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/7.jpg)
ITERATIONP
ATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecifiedcomparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
JCFproblems
• Whyisn’tsort()amethodoneveryList?Collections.sort(list,comparator);
vs.list.sort(comparator);
7
![Page 8: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/8.jpg)
ITERATIONP
ATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecifiedcomparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
JCFproblems
• WherearealltheiteraFonpaWerns?• java.util.Collectionsprovidesmethodsforsort(),min(),max()andjustafewothers.
• ThemostcommoniteraFonpaWernsaremissing:• Collectalistofeachperson’sfirstname.• Selectonlythosepeoplewhoselastnameis“Smith”.
8
![Page 9: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/9.jpg)
ITERATIONP
ATTERNS
Itera+onPaLerns
• Wewantthemethodssort(),min(),max(),collect(),select(),etc.oneverycollecFon.
• Howcanweaccomplishthisincode?• CreateinterfacesthatextendtheJCFinterfaces.
EclipseCollec+onsInterfaces
publicinterfaceMutableList<T>extendsList<T>{MutableList<T>sortThis(Comparator<?superT>comparator);<V>MutableList<V>collect(Function<?superT,?extendsV>function);
MutableList<T>select(Predicate<?superT>predicate);...}
9
![Page 10: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/10.jpg)
COLLECTP
ATTERNItera+onPaLern
• CollectpaWern(akamaportransform).• ReturnsanewcollecFonwhereeachelementhasbeentransformed
• e.g.collecteachpet’sname.
• Functionisthetypethattakesanobjectandreturnsanobjectofadifferenttype• akaTransformer
JCFExample
List<Pet>pets=...
List<String>petNames=newArrayList<String>();for(Petpet:pets){ petNames.add(pet.getName());}
10
![Page 11: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/11.jpg)
COLLECTP
ATTERNItera+onPaLern
• Functionisthetypethattakesanobjectandreturnsanothertype.
EclipseCollec+onsExample(AnonymousInnerClassSyntax)
MutableList<Pet>pets=...
MutableList<String>petNames=pets.collect(newFunction<Pet,String>(){publicStringvalueOf(Petpet){returnpet.getName();}});
11
![Page 12: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/12.jpg)
COLLECTP
ATTERNItera+onPaLern
• Functionisthetypethattakesanobjectandreturnsanothertype.
EclipseCollec+onsExample(Java8)
MutableList<Pet>pets=...
MutableList<String>petNames=pets.collect(pet->pet.getName());
MutableList<String>petNames=pets.collect(Pet::getName);
12
![Page 13: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/13.jpg)
SELECTPATTERN
Itera+onPaLern
• SelectpaWern(akafilter).• ReturnstheelementsofacollecFonthatsaFsfysomecondiFon
• e.g.selectonlythosepeoplewhohaveapet.• Predicateisthetypethattakesanobjectandreturnsaboolean.
EclipseCollec+onsExample(AnonymousInnerClassSyntax)
MutableList<Person>people=...
MutableList<Person>petPeople=people.select(newPredicate<Person>(){publicbooleanaccept(Personperson){returnperson.isPetPerson();}}); 13
![Page 14: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/14.jpg)
SELECTPATTERN
Itera+onPaLern
• SelectpaWern(akafilter).• ReturnstheelementsofacollecFonthatsaFsfysomecondiFon
• e.g.selectonlythosepeoplewhohaveapet.• Predicateisthetypethattakesanobjectandreturnsaboolean.
EclipseCollec+onsExample(Java8)
MutableList<Person>people=...
MutableList<Person>petPeople=people.select(person->person.isPetPerson());
14
![Page 15: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/15.jpg)
ITERATIONP
ATTERNS
Examples
Collect ReturnsanewcollecFonwhereeachelementhasbeentransformed.
Select ReturnstheelementsofacollecFonthatsaFsfysomecondiFon.
CodeBlocks
• sortThis()takesaComparator,whichisastrategyinterface.• Similarly,collect()andselect()take“codeblock”parameters.• collect()takesaFunction.• select()takesaPredicate.• Don’tgethunguponthesenamesbecausetheIDEwillremindyou.
15
![Page 16: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/16.jpg)
KATAINTRODUCTION
16
![Page 17: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/17.jpg)
KATAIN
TRODU
CTION
Domain
• EclipseCollecFonsMiniKatausesPerson,Pet,PetType• Dataisavailabletoyouthroughthis.peoplewhichhassomepersonandpetobjectssetforyou
17
![Page 18: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/18.jpg)
KATAIN
TRODU
CTION
Domain
18
![Page 19: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/19.jpg)
KATAEXERCISE1
19
![Page 20: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/20.jpg)
KATA
Exercise1
• FixExercise1Test;theyhavefailures.• Figureouthowtogettheteststopassusingwhatyouhaveseensofar.• Shouldtakeabout15minutes.
20
![Page 21: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/21.jpg)
TESTUTILS
21
![Page 22: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/22.jpg)
TESTUTILS
Verify
• EclipseCollecFonsdistribuFonincludeseclipse-collec+ons-testu+ls.jar.• IncludeshelpfuluFlityforwriFngunittests.• CollecFon-specific.• ImplementedasanextensionofJUnit.• BeWererrormessages• MostimportantclassiscalledVerify.
CodeExample
ExamplefromtheprevioussoluFonVerify.assertSize(2,peopleWithCats);InsteadofAssert.assertEquals(2,peopleWithCats.size());
22
![Page 23: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/23.jpg)
FLATCOLLECTPATTERN
23
![Page 24: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/24.jpg)
FLATCOLLECTP
ATTERNBackgroundoncollect()
• flatCollect()isaspecialcaseofcollect().• Withcollect(),whentheFunctionreturnsacollecFon,theresultisacollecFonofcollecFons.
CodeExampleMutableList<Person>people=...;Function<Person,Iterable<PetType>>function=
person->person.getPetTypes();
MutableList<MutableList<PetType>>pets=people.collect(function);
24
![Page 25: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/25.jpg)
FLATCOLLECTP
ATTERNflatCollect()
• flatCollect()outputsasingle“flaWened”collecFoninsteadofacollecFonofcollecFons.
• ThesignatureofflatCollect()issimilartocollect(),exceptthattheFunctionparametermustmaptoanIterabletype.
flatCollect(Function<?superT,?extendsIterable<V>>function);
CodeExampleMutableList<Person>people=...;
MutableList<PetType>pets=people.flatCollect(person->person.getPetTypes());
25
![Page 26: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/26.jpg)
MOREITERATIONPATTERNS
26
![Page 27: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/27.jpg)
ITERATIONP
ATTERNS
OtherpaLernsthatusePredicate
Short-circuitpaLernsthatusePredicate
27
Select ReturnstheelementsofacollecFonthatsaFsfythePredicate.
Reject ReturnstheelementsofacollecFonthatdonotsaFsfythePredicate.
Count ReturnsthenumberofelementsthatsaFsfythePredicate.
Detect FindsthefirstelementthatsaFsfiesthePredicate.
AnySa+sfy ReturnstrueifanyelementsaFsfiesthePredicate.
AllSa+sfy ReturnstrueifallelementssaFsfythePredicate.
![Page 28: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/28.jpg)
ITERATIONP
ATTERNS
InheritanceHierarchy
• MutableListextendsList.• FastListisadrop-inreplacementforArrayList.
28
Lists
![Page 29: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/29.jpg)
ITERATIONP
ATTERNS
InheritanceHierarchy Sets
• MutableSetextendsSet.• UnifiedSetisadropinreplacementforHashSet.
29
![Page 30: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/30.jpg)
“WITH”METHODS
30
![Page 31: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/31.jpg)
“WITH”M
ETHODS
collectWith(),selectWith(),andrejectWith()
• collectWith(),selectWith(),andrejectWith()arealternateformsofcollect(),select(),andreject().
• Originalformsalltakeasingleparameter,acodeblockwhichtakesasingleparameter.
• Whatifwewanttofindgroupsofpeopleatdifferentages?
CodeExample
MutableList<Person>voters=people.select(person->person.getAge()>18;);
![Page 32: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/32.jpg)
“WITH”M
ETHODS
collectWith(),selectWith(),andrejectWith()
• collectWith(),selectWith(),andrejectWith()arealternateformsofcollect(),select(),andreject().
• …with()formstaketwoparameters:• acodeblockwhichtakestwoparameters,• anobjectthatgetspassedasthesecondargumenttothecodeblock.
• Storethetwo-argumentblockinaconstanttoavoidobjectcreaFon.
CodeExample
Predicate2<Person,Integer>age=(person,age)->person.getAge()>age;MutableList<Person>drivers=people.selectWith(age,17);MutableList<Person>voters=people.selectWith(age,18);MutableList<Person>drinkers=people.selectWith(age,21);MutableList<Person>sunsetRobotSquad=people.selectWith(age,160);
![Page 33: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/33.jpg)
“WITH”M
ETHODS
ForalmosteverycommoniteraFonpaWern,thereisanequivalent“With”method.
- selectWith()- detectWith()- rejectWith()- anySatisfyWith()…etc
Howtheycanbeused
Theseareusefulwhenyouwanttousemethodreferencesratherthanlambdas.
//doesnotcompileMutableList<Person>peopleWithCatsLambda=this.people.select(Person::hasPet(PetType.CAT));
33
![Page 34: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/34.jpg)
“WITH”M
ETHODS
ForalmosteverycommoniteraFonpaWern,thereisanequivalent“With”method.
- selectWith()- detectWith()- rejectWith()- anySatisfyWith()…etc
Howtheycanbeused
Theseareusefulwhenyouwanttousemethodreferencesratherthanlambdas.
MutableList<Person>peopleWithCatMethodReference=
this.people.selectWith(Person::hasPet,PetType.CAT);
34
![Page 35: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/35.jpg)
KATAEXERCISE2
35
![Page 36: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/36.jpg)
KATA
Exercise2
• FixExercise2Test.• UsetheotheriteraFonpaWernsthattakeaPredicate.• UsetheflatCollectpaWern• Shouldtakeabout15minutes.
36
![Page 37: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/37.jpg)
BAG
37
![Page 38: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/38.jpg)
BAG
NewType
• UsefulwhenyouwouldotherwiseuseMap<K,Integer>• Forexample,findthenumberofeachpettype.
CodeExample
MutableList<Person>people=...;MutableList<PetType>pets=
people.flatCollect(Person::getPetTypes);MutableMap<PetType,Integer>petTypeCounts=
UnifiedMap.newMap();...intcats=petTypeCounts.get(PetType.CAT);
38
![Page 39: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/39.jpg)
BAG
NewType
• UsefulwhenyouwouldotherwiseuseMap<K,Integer>• Forexample,findthenumberofeachpettype.• LotsofboilerplatecodetodealwithuniniFalizedcounts.
MapExample
MutableMap<PetType,Integer>petTypeCounts=UnifiedMap.newMap();
for(PetTypepetType:pets){Integercount=petTypeCounts.get(petType);if(count==null){count=0;}petTypeCounts.put(petType,count+1);} 39
![Page 40: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/40.jpg)
BAG
NewType
• Implementedasamapofkeytocount.• LikeaList,butunordered.• LikeaSet,butallowsduplicates.
BagExample
MutableBag<PetType>petTypeCounts=pets.toBag();intcat=petTypeCounts.occurrencesOf(PetType.CAT);
40
![Page 41: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/41.jpg)
BAG
BagAPI
CodeExample
MutableBag<String>bag=HashBag.newBagWith("one","two","two","three","three","three");
Assert.assertEquals(3,bag.occurrencesOf("three"));
bag.add("one");Assert.assertEquals(2,bag.occurrencesOf("one"));
bag.addOccurrences("one",4);Assert.assertEquals(6,bag.occurrencesOf("one"));
41
Methods Inheritedfrom
select(),collect(),etc. RichIterableadd(),remove(),iterator(),etc.
MutableCollection(java.util.Collection)
occurrencesOf(),forEachWithOccurrences(),toMapOfItemToCount()
Bag
addOccurrences(),removeOccurrences() MutableBag
![Page 42: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/42.jpg)
MULTIMAP
42
![Page 43: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/43.jpg)
MULTIM
APNewType
• MultimapissimilartoMap,butassociatesakeytomul=plevalues.• UsefulwhenyouwouldotherwiseuseMap<K,Collection<V>>
• Forexample,findwhichpeoplehavethesamelastname.
CodeExample
MutableList<Person>people=...;MutableMap<String,MutableList<Person>>
lastNamesToPeople=UnifiedMap.newMap();...MutableList<Person>smiths=
lastNamesToPeople.get("Smith");43
![Page 44: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/44.jpg)
MULTIM
APNewType
• MultimapissimilartoMap,butassociatesakeytomul=plevalues.• UsefulwhenyouwouldotherwiseuseMap<K,Collection<V>>
• Forexample,findwhichpeoplehavethesamelastname.• LotsofboilerplatecodetodealwithuniniFalizedbackingcollecFons.
MapExample
MutableMap<String,MutableList<Person>>lastNamesToPeople=UnifiedMap.newMap();
for(Personperson:people){StringlastName=person.getLastName();MutableList<Person>peopleWithLastName=
lastNamesToPeople.get(lastName);if(peopleWithLastName==null){peopleWithLastName=FastList.newList();lastNamesToPeople.put(lastName,peopleWithLastName);}peopleWithLastName.add(person);} 44
![Page 45: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/45.jpg)
MULTIM
APBefore
A\er
45
MutableMap<String,MutableList<Person>>lastNamesToPeople=UnifiedMap.newMap();
for(Personperson:people){StringlastName=person.getLastName();MutableList<Person>peopleWithLastName=
lastNamesToPeople.get(lastName);if(peopleWithLastName==null){peopleWithLastName=FastList.newList();lastNamesToPeople.put(lastName,peopleWithLastName);}peopleWithLastName.add(person);}
MutableListMultimap<String,Person>lastNamesToPeople=people.groupBy(Person.TO_LAST_NAME);MutableList<Person>smiths=
lastNamesToPeople.get("Smith");
![Page 46: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/46.jpg)
MULTIM
APMul+map
• Whathappensifyouaddthesamekeyandvaluetwice?
CodeExample
MutableMultimap<String,Person>multimap=...;multimap.put("Smith",person);multimap.put("Smith",person);RichIterable<Person>smiths=
multimap.get("Smith");
Verify.assertIterableSize(?,smiths);46
![Page 47: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/47.jpg)
MULTIM
APMul+map
• Whathappensifyouaddthesamekeyandvaluetwice?• DependsonthetypeofthebackingcollecFon.
CodeExample
MutableListMultimap<String,Person>multimap=FastListMultimap.newMultimap();multimap.put("Smith",person);multimap.put("Smith",person);MutableList<Person>smiths=multimap.get("Smith");
Verify.assertIterableSize(2,smiths);47
![Page 48: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/48.jpg)
MULTIM
APMul+map
• Whathappensifyouaddthesamekeyandvaluetwice?• DependsonthetypeofthebackingcollecFon.
CodeExample
MutableSetMultimap<String,Person>multimap=UnifiedSetMultimap.newMultimap();multimap.put("Smith",person);multimap.put("Smith",person);MutableSet<Person>smiths=multimap.get("Smith");
Verify.assertIterableSize(1,smiths);48
![Page 49: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/49.jpg)
MULTIM
APgroupByEach()
• groupByEach()isaspecialcaseofgroupBy().• Analogoustothedifferencebetweencollect()andflatCollect().• AppropriatewhentheFunctionreturnsacollecFon.• ThereturntypeisthesameasgroupBy().
CodeExampleMutableListMultimap<String,Person>lastNamesToPeople=people.groupBy(LAST_NAME_FUNCTION);MutableListMultimap<PetType,Person>petsToPeople=people.groupByEach(PET_TYPE_FUNCTION);
49
![Page 50: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/50.jpg)
TARGETCOLLECTIONS
50
![Page 51: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/51.jpg)
TARGETCOLLECTIO
NS
Itera+onPaLern
• Let'ssaywehave3people:mrSmith,mrsSmith,mrJones.• Thefirsttwosharethesameaddress.• Whatwillgetprintedbythefollowingcode?
ExampleCode
MutableSet<Person>people=UnifiedSet.newSetWith(mrSmith,mrsSmith,mrJones);intnumAddresses=people.collect(addressFunction).size();System.out.println(numAddresses);
51
![Page 52: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/52.jpg)
TARGETCOLLECTIO
NS
Covariantreturntypes
• select(),collect(),etc.aredefinedwithcovariantreturntypes:
• MutableCollection.collect()returnsaMutableCollection• MutableList.collect()returnsaMutableList• MutableSet.collect()returnsaMutableSet
• AlternateformstaketargetcollecFons.
ExampleCode
MutableSet<Person>people=UnifiedSet.newSetWith(mrSmith,mrsSmith,mrJones);intnumAddresses=people.collect(addressFunction).size();System.out.println(numAddresses);
52
![Page 53: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/53.jpg)
TARGETCOLLECTIO
NS
Covariantreturntypes
• select(),collect(),etc.aredefinedwithcovariantreturntypes:
• MutableCollection.collect()returnsaMutableCollection• MutableList.collect()returnsaMutableList• MutableSet.collect()returnsaMutableSet
• AlternateformstaketargetcollecFons.
ExampleCode
MutableSet<Person>people=UnifiedSet.newSetWith(mrSmith,mrsSmith,mrJones);
MutableList<Address>targetList=FastList.<Address>newList();intnumAddresses=
people.collect(addressFunction,targetList).size();System.out.println(numAddresses); 53
![Page 54: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/54.jpg)
KATAEXERCISE3
54
![Page 55: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/55.jpg)
KATA
Exercise3
• FixExercise3Test.• UseBag,MulFmap.• Shouldtakeabout10minutes.
55
![Page 56: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/56.jpg)
PRIMITIVECOLLECTIONS
![Page 57: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/57.jpg)
PRIM
ITIVECOLLECTIO
NS
EachdatastructurehasanequivalentprimiFveside.EclipseCollecFonssupportsallprimiFves–int,double,short,long,
float,boolean,char,byte
57
![Page 58: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/58.jpg)
PRIM
ITIVECOLLECTIO
NS
ClassDiagram
PrimiFveIterable IntIterable
MutableIntCollecFon
MutableIntList
MutableIntSet
MutableIntBag
LazyIntIterable
ImmutableIntCollecFon
ImmutableIntList
ImmutableIntSet
ImmutableIntBag
58
![Page 59: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/59.jpg)
PRIM
ITIVECOLLECTIO
NS
Primi+veAPI
ThereisalsothesamerichandfluentAPIthatthenonprimiFvesideoffers.
Examples
MutableIntListintListOfAges=this.people.flatCollect(Person::getPets) .collectInt(Pet::getAge);
MutableIntListselection= intListOfAges.select(age->age>2);
MutableIntSetintSetOfAges=intListOfAges.toSet();
59
![Page 60: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/60.jpg)
KATAEXERCISE4
60
![Page 61: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/61.jpg)
KATA
Exercise4
• FixExercise4Test.• RefactorJava8streamstoEclipseCollecFons.• Shouldtakeabout20minutes.
61
![Page 62: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/62.jpg)
KATAEXERCISE5
62
![Page 63: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/63.jpg)
KATA
Exercise4
• FixExercise5Test.• Thisisextra-credit• Usetargetversions,methodsonRichIterable• Shouldtakeabout20minutes.
63
![Page 64: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/64.jpg)
APPENDIX
64
![Page 65: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/65.jpg)
ANONYMOUSINNERCLASS
65
![Page 66: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/66.jpg)
ANONYM
OUSIN
NERC
LASSDefini+on
• Aninnerclasswithnoname.• Lookslikeanormalconstructorcall,butitworksonabstracttypes(includinginterfaces).
• HasabodyarerwardswhichmakesthetypeconcreteoroverridesmethoddefiniFons.
• Hasarandom-lookingclassnamearercompilaFon.• OuterClass$1forthefirstanonymousinnerclassinOuterClass.
CodeExample
Comparator<Person>comparator=newComparator<Person>(){publicintcompare(Persono1,Persono2){returno1.getLastName().compareTo(o2.getLastName());}};System.out.println(comparator.getClass());
66
![Page 67: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/67.jpg)
CLOSURE
67
![Page 68: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/68.jpg)
CLO
SURE
ClosureDefini+on
WikipediadefiniFon:“[A]closureisafirst-classfuncFonwithfreevariablesthatareboundinthelexicalenvironment.“SuchafuncFonissaidtobe‘closedover’itsfreevariables.“Aclosureisdefinedwithinthescopeofitsfreevariables,andtheextentofthosevariablesisatleastaslongasthelifeFmeoftheclosureitself.”
• Javadoesnothaveclosures.• Java8haslambdas.
68
![Page 69: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/69.jpg)
CLO
SURE
ClosureDefini+on
Javadoesnothaveclosures.Inthecodeexample,thePredicateisaclasswithaStringfield.Itisnotthesamecopyasthemethodparameter.
CodeExample
publicCustomergetCustomerNamed(Stringname){Predicate<Customer>customerNamed=Predicates.attributeEqual(Customer.TO_NAME,name);returnthis.customers.detect(customerNamed);}
69
![Page 70: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/70.jpg)
CLO
SURE
ClosureDefini+on
Javadoesnothaveclosures.Inthecodeexample,thePredicateisaclasswithaStringfield.Itisnotthesamecopyasthemethodparameter.• Changingthiscopyofnamehasnoeffectontheresult.• MaybeobviousbecauseofJava’srulesforparameterpassing.
CodeExample
publicCustomergetCustomerNamed(Stringname){Predicate<Customer>customerNamed=Predicates.attributeEqual(Customer.TO_NAME,name);name=name+"!";returnthis.customers.detect(customerNamed);}
70
![Page 71: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/71.jpg)
CLO
SURE
ClosureDefini+on
Javadoesnothaveclosures.Inthecodeexample,thePredicateisaclasswithaStringfield.Itisnotthesamecopyasthemethodparameter.• IfyouuseananonymousinnerclasstoimplementthePredicate,youhavetomakenamefinalinordertosaFsfythecompiler.
CodeExample
publicCustomergetCustomerNamed(finalStringname){Predicate<Customer>attributeEqual=newPredicate<Customer>(){publicbooleanaccept(Customercustomer){returncustomer.getName().equals(name);}};returnthis.customers.detect(attributeEqual);} 71
![Page 72: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/72.jpg)
CLO
SURE
ClosureDefini+on
Javadoesnothaveclosures.Inthecodeexample,thePredicateisaclasswithaStringfield.Itisnotthesamecopyasthemethodparameter.• IfyouuseananonymousinnerclasstoimplementthePredicate,youhavetomakenamefinalinordertosaFsfythecompiler.
• Refactortheanonymousinnerclasstoanamedinnerclassandyoucanseewhy.
CodeExample
privatestaticfinalclassCustomerNamedimplementsPredicate<Customer>{
privatefinalStringname;privateCustomerNamed(Stringname){this.name=name;}publicbooleanaccept(Customercustomer){returncustomer.getName().equals(this.name);}} 72
![Page 73: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/73.jpg)
BLOCKS
73
![Page 74: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/74.jpg)
BLO
CKSUML
74
![Page 75: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/75.jpg)
BLO
CKSFunc+on
Functiontransformsonetype(T)toanother(V):publicinterfaceFunction<T,V>extendsSerializable{VvalueOf(Tobject);}
Usedin:• collect• flatCollect• groupBy• minBy• maxBy• toSortedListBy• sortThisBy• toMap
75
![Page 76: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/76.jpg)
BLO
CKSPredicate
Predicatetakesanobjectofsometype(T)andreturnsaboolean:publicinterfacePredicate<T>extendsSerializable{booleanaccept(finalTeach);}
Usedin:• select• reject• detect• count• anySatisfy• allSatisfy
76
![Page 77: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/77.jpg)
BLO
CKSPredicate
Proceduretakesanobjectofsometype(T)anddoesn’treturnanything:publicinterfaceProcedure<T>extendsSerializable{voidvalue(finalTeach);}
Usedin:• forEach
77
![Page 78: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/78.jpg)
RICHITERABLE
78
![Page 79: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/79.jpg)
RICHITERABLE
CheatSheet
79
collect TransformselementsusingaFunctionintoanewcollecFon.
flatCollect TransformsandflaWenstheelementsusingaFunction.
groupBy GetsakeyforeachelementusingaFunctionandputsthekeyandelementintoaMultimap.
![Page 80: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/80.jpg)
RICHITERABLE
CheatSheet
80
sortThisBy GetssomeaWributefromeachelementusingaFunctionandsortsthelistbythenaturalorderofthataWribute.
toSortedListBy GetssomeaWributefromeachelementusingaFunctionandreturnsanewlistsortedbythenaturalorderofthataWribute.
minBy GetssomeaWributefromeachelementandreturnstheelementwhoseaWributeisminimal.
maxBy GetssomeaWributefromeachelementandreturnstheelementwhoseaWributeismaximal.
toMap GetsakeyandvalueforeachelementusingtwoFunctionsandreturnsanewmapcontainingallthekey/valuepairs.
![Page 81: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/81.jpg)
RICHITERABLE
CheatSheet
81
select ReturnstheelementsofacollecFonthatsaFsfysomecondiFon(Predicate).
reject ReturnstheelementsofacollecFonthatdonotsaFsfythePredicate.
detect FindsthefirstelementthatsaFsfiesthePredicate.
count ReturnsthenumberofelementsthatsaFsfythePredicate.
anySatisfy ReturnstrueifanyelementsaFsfiesthePredicate.
allSatisfy ReturnstrueifallelementssaFsfythePredicate.
forEach ExecutestheProcedureoneachelement,doesn'treturnanything.
![Page 82: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/82.jpg)
RICHITERABLE
CheatSheet
82
min ReturnstheminimumelementusingeitherthenaturalorderoraComparator.
max ReturnsthemaximumelementusingeitherthenaturalorderoraComparator.
toSortedList Returnsanewlist,sortedusingeitherthenaturalorderoraComparator.
makeString ConvertsthecollecFontoastringusingopFonalstart,end,andseparatorstrings.
appendString ConvertsthecollecFontoastringandappendsittoanAppendable.
zip TakesasecondRichIterableandpairsupalltheelements.IfoneofthetwoRichIterablesislongerthantheother,itsremainingelementsareignored.
zipWithIndex ZipsthecollecFonwiththeIntegerindexes0ton-1.
chunk SplitsacollecFonintofixedsizechunks.ThefinalchunkwillbesmallerifthecollecFondoesn'tdivideevenly.
![Page 83: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/83.jpg)
RICHITERABLE
InheritanceHierarchy
83
![Page 84: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/84.jpg)
BAG
ClassDiagram
Iterable RichIterable
MutableCollecFon
MutableList
MutableSet
MutableBag
ImmutableCollecFon
ImmutableList
ImmutableSet
ImmutableBag
84
![Page 85: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/85.jpg)
BAG
ClassDiagram
RichIterable Bag
MutableBag
HashBag
SynchronizedBag
UnmodifiableBagImmutableBag
85
![Page 86: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/86.jpg)
MULTIM
APClassDiagram
MulFmap
MutableMulFmap
MutableListMulFmap
MutableSetMulFmap
MutableBagMulFmap
ImmutableMulFmap
ImmutableListMulFmap
ImmutableSetMulFmap
ImmutableBagMulFmap
86
![Page 87: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/87.jpg)
OPTIMIZATION
87
![Page 88: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/88.jpg)
OPTIM
IZATION
collectWith(),selectWith(),andrejectWith()
• collectWith(),selectWith(),andrejectWith()arealternateformsofcollect(),select(),andreject().
• Originalformsalltakeasingleparameter,acodeblockwhichtakesasingleparameter.
• Whatifwewanttofindgroupsofpeopleatdifferentages?
CodeExample
MutableList<Person>voters=people.select(person->person.getAge()>18;);
88
![Page 89: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/89.jpg)
OPTIM
IZATION
collectWith(),selectWith(),andrejectWith()
• collectWith(),selectWith(),andrejectWith()arealternateformsofcollect(),select(),andreject().
• …with()formstaketwoparameters:• acodeblockwhichtakestwoparameters,• anobjectthatgetspassedasthesecondargumenttothecodeblock.
• Storethetwo-argumentblockinaconstanttoavoidobjectcreaFon.
CodeExample
Predicate2<Person,Integer>age=(person,age)->person.getAge()>age;MutableList<Person>drivers=people.selectWith(age,17);MutableList<Person>voters=people.selectWith(age,18);MutableList<Person>drinkers=people.selectWith(age,21);MutableList<Person>sunsetRobotSquad=people.selectWith(age,160);
89
![Page 90: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/90.jpg)
OPTIM
IZATION
“Weshouldforgetaboutsmallefficiencies,sayabout97%oftheFme:prematureopFmizaFonistherootofallevil”
–DonaldKnuth
90
![Page 91: Eclipse Collec+ons and Java 8 Lambdas · • java.util.Collections provides methods for sort(), min(), max() and just a few others. • The most common iteraon paerns are missing:](https://reader035.vdocuments.us/reader035/viewer/2022062919/5ee194eead6a402d666c68ac/html5/thumbnails/91.jpg)
Learn more at GS.com/Engineering
© 2016 Goldman Sachs. This presentation should not be relied upon or considered investment advice. Goldman Sachs does not warrant or guarantee to anyone the accuracy, completeness or efficacy of this presentation, and recipients should not rely on it except at their own risk. This presentation may not be forwarded or disclosed except with this disclaimer intact.