Upload
others
View
6
Download
0
Embed Size (px)
Citation preview
EclipseCollec+onsandJava8Lambdas
MiniCodeKataBasicIdeas,BasicImplementa+onsMarch2016
Copyright©2016GoldmanSachs.Allrightsreserved.
INTRO
WhatisEclipseCollec+ons?
• AsupplementorreplacementfortheJavaCollecFonsFramework(JCF).• DevelopedoriginallyatGoldmanSachs.• "Inspiredby"SmalltalkCollecFonprotocol.
2
WhatisaCodeKata?
• AprogrammingexercisewhichhelpshoneyourskillsthroughpracFce.• Thisoneissetupasaseriesofunittestswhichfail.• Yourtaskistomakethempass,usingEclipseCollecFons–
IhearandIforget.IseeandIremember.IdoandIunderstand.
-Confucius
EclipseCollec+onsMiniCodeKata
• Newconceptsareintroducedintheslides• CodingexercisesareattheendofeachsecFon.
ITERATIONPATTERNS
3
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
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
ITERATIONP
ATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecifiedcomparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
6
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
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
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
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
COLLECTP
ATTERNItera+onPaLern
• Functionisthetypethattakesanobjectandreturnsanothertype.
EclipseCollec+onsExample(AnonymousInnerClassSyntax)
MutableList<Pet>pets=...
MutableList<String>petNames=pets.collect(newFunction<Pet,String>(){publicStringvalueOf(Petpet){returnpet.getName();}});
11
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
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
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
ITERATIONP
ATTERNS
Examples
Collect ReturnsanewcollecFonwhereeachelementhasbeentransformed.
Select ReturnstheelementsofacollecFonthatsaFsfysomecondiFon.
CodeBlocks
• sortThis()takesaComparator,whichisastrategyinterface.• Similarly,collect()andselect()take“codeblock”parameters.• collect()takesaFunction.• select()takesaPredicate.• Don’tgethunguponthesenamesbecausetheIDEwillremindyou.
15
KATAINTRODUCTION
16
KATAIN
TRODU
CTION
Domain
• EclipseCollecFonsMiniKatausesPerson,Pet,PetType• Dataisavailabletoyouthroughthis.peoplewhichhassomepersonandpetobjectssetforyou
17
KATAIN
TRODU
CTION
Domain
18
KATAEXERCISE1
19
KATA
Exercise1
• FixExercise1Test;theyhavefailures.• Figureouthowtogettheteststopassusingwhatyouhaveseensofar.• Shouldtakeabout15minutes.
20
TESTUTILS
21
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
FLATCOLLECTPATTERN
23
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
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
MOREITERATIONPATTERNS
26
ITERATIONP
ATTERNS
OtherpaLernsthatusePredicate
Short-circuitpaLernsthatusePredicate
27
Select ReturnstheelementsofacollecFonthatsaFsfythePredicate.
Reject ReturnstheelementsofacollecFonthatdonotsaFsfythePredicate.
Count ReturnsthenumberofelementsthatsaFsfythePredicate.
Detect FindsthefirstelementthatsaFsfiesthePredicate.
AnySa+sfy ReturnstrueifanyelementsaFsfiesthePredicate.
AllSa+sfy ReturnstrueifallelementssaFsfythePredicate.
ITERATIONP
ATTERNS
InheritanceHierarchy
• MutableListextendsList.• FastListisadrop-inreplacementforArrayList.
28
Lists
ITERATIONP
ATTERNS
InheritanceHierarchy Sets
• MutableSetextendsSet.• UnifiedSetisadropinreplacementforHashSet.
29
“WITH”METHODS
30
“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;);
“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);
“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
“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
KATAEXERCISE2
35
KATA
Exercise2
• FixExercise2Test.• UsetheotheriteraFonpaWernsthattakeaPredicate.• UsetheflatCollectpaWern• Shouldtakeabout15minutes.
36
BAG
37
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
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
BAG
NewType
• Implementedasamapofkeytocount.• LikeaList,butunordered.• LikeaSet,butallowsduplicates.
BagExample
MutableBag<PetType>petTypeCounts=pets.toBag();intcat=petTypeCounts.occurrencesOf(PetType.CAT);
40
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
MULTIMAP
42
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
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
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");
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
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
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
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
TARGETCOLLECTIONS
50
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
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
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
KATAEXERCISE3
54
KATA
Exercise3
• FixExercise3Test.• UseBag,MulFmap.• Shouldtakeabout10minutes.
55
PRIMITIVECOLLECTIONS
PRIM
ITIVECOLLECTIO
NS
EachdatastructurehasanequivalentprimiFveside.EclipseCollecFonssupportsallprimiFves–int,double,short,long,
float,boolean,char,byte
57
PRIM
ITIVECOLLECTIO
NS
ClassDiagram
PrimiFveIterable IntIterable
MutableIntCollecFon
MutableIntList
MutableIntSet
MutableIntBag
LazyIntIterable
ImmutableIntCollecFon
ImmutableIntList
ImmutableIntSet
ImmutableIntBag
58
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
KATAEXERCISE4
60
KATA
Exercise4
• FixExercise4Test.• RefactorJava8streamstoEclipseCollecFons.• Shouldtakeabout20minutes.
61
KATAEXERCISE5
62
KATA
Exercise4
• FixExercise5Test.• Thisisextra-credit• Usetargetversions,methodsonRichIterable• Shouldtakeabout20minutes.
63
APPENDIX
64
ANONYMOUSINNERCLASS
65
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
CLOSURE
67
CLO
SURE
ClosureDefini+on
WikipediadefiniFon:“[A]closureisafirst-classfuncFonwithfreevariablesthatareboundinthelexicalenvironment.“SuchafuncFonissaidtobe‘closedover’itsfreevariables.“Aclosureisdefinedwithinthescopeofitsfreevariables,andtheextentofthosevariablesisatleastaslongasthelifeFmeoftheclosureitself.”
• Javadoesnothaveclosures.• Java8haslambdas.
68
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
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
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
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
BLOCKS
73
BLO
CKSUML
74
BLO
CKSFunc+on
Functiontransformsonetype(T)toanother(V):publicinterfaceFunction<T,V>extendsSerializable{VvalueOf(Tobject);}
Usedin:• collect• flatCollect• groupBy• minBy• maxBy• toSortedListBy• sortThisBy• toMap
75
BLO
CKSPredicate
Predicatetakesanobjectofsometype(T)andreturnsaboolean:publicinterfacePredicate<T>extendsSerializable{booleanaccept(finalTeach);}
Usedin:• select• reject• detect• count• anySatisfy• allSatisfy
76
BLO
CKSPredicate
Proceduretakesanobjectofsometype(T)anddoesn’treturnanything:publicinterfaceProcedure<T>extendsSerializable{voidvalue(finalTeach);}
Usedin:• forEach
77
RICHITERABLE
78
RICHITERABLE
CheatSheet
79
collect TransformselementsusingaFunctionintoanewcollecFon.
flatCollect TransformsandflaWenstheelementsusingaFunction.
groupBy GetsakeyforeachelementusingaFunctionandputsthekeyandelementintoaMultimap.
RICHITERABLE
CheatSheet
80
sortThisBy GetssomeaWributefromeachelementusingaFunctionandsortsthelistbythenaturalorderofthataWribute.
toSortedListBy GetssomeaWributefromeachelementusingaFunctionandreturnsanewlistsortedbythenaturalorderofthataWribute.
minBy GetssomeaWributefromeachelementandreturnstheelementwhoseaWributeisminimal.
maxBy GetssomeaWributefromeachelementandreturnstheelementwhoseaWributeismaximal.
toMap GetsakeyandvalueforeachelementusingtwoFunctionsandreturnsanewmapcontainingallthekey/valuepairs.
RICHITERABLE
CheatSheet
81
select ReturnstheelementsofacollecFonthatsaFsfysomecondiFon(Predicate).
reject ReturnstheelementsofacollecFonthatdonotsaFsfythePredicate.
detect FindsthefirstelementthatsaFsfiesthePredicate.
count ReturnsthenumberofelementsthatsaFsfythePredicate.
anySatisfy ReturnstrueifanyelementsaFsfiesthePredicate.
allSatisfy ReturnstrueifallelementssaFsfythePredicate.
forEach ExecutestheProcedureoneachelement,doesn'treturnanything.
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.
RICHITERABLE
InheritanceHierarchy
83
BAG
ClassDiagram
Iterable RichIterable
MutableCollecFon
MutableList
MutableSet
MutableBag
ImmutableCollecFon
ImmutableList
ImmutableSet
ImmutableBag
84
BAG
ClassDiagram
RichIterable Bag
MutableBag
HashBag
SynchronizedBag
UnmodifiableBagImmutableBag
85
MULTIM
APClassDiagram
MulFmap
MutableMulFmap
MutableListMulFmap
MutableSetMulFmap
MutableBagMulFmap
ImmutableMulFmap
ImmutableListMulFmap
ImmutableSetMulFmap
ImmutableBagMulFmap
86
OPTIMIZATION
87
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
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
OPTIM
IZATION
“Weshouldforgetaboutsmallefficiencies,sayabout97%oftheFme:prematureopFmizaFonistherootofallevil”
–DonaldKnuth
90
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.