slides - EclipseCon

Transcription

slides - EclipseCon
EclipseCollec+onsandJava8Lambdas
MiniCodeKata
BasicIdeas,BasicImplementa+ons
March2016
Copyright©2016GoldmanSachs.Allrightsreserved.
• AsupplementorreplacementfortheJavaCollecFonsFramework(JCF).
• DevelopedoriginallyatGoldmanSachs.
• "Inspiredby"SmalltalkCollecFonprotocol.
WhatisaCodeKata?
• AprogrammingexercisewhichhelpshoneyourskillsthroughpracFce.
• Thisoneissetupasaseriesofunittestswhichfail.
• Yourtaskistomakethempass,usingEclipseCollecFons–
IhearandIforget.
IseeandIremember.
IdoandIunderstand.
-Confucius
EclipseCollec+onsMiniCodeKata
• Newconceptsareintroducedintheslides
• CodingexercisesareattheendofeachsecFon.
2
INTRO
WhatisEclipseCollec+ons?
I TERATION P ATTERNS 3
ITERATIONPATTERNS
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
publicstaticvoidjava.util.Collections.sort(
List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecified
comparator.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
ITERATIONPATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(
List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecified
comparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
6
ITERATIONPATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(
List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecified
comparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
JCFproblems
• Whyisn’tsort()amethodoneveryList?
Collections.sort(list,comparator);
vs.
list.sort(comparator);
7
ITERATIONPATTERNS
Javadoc
publicstaticvoidjava.util.Collections.sort(
List<T>list,Comparator<?superT>c)
Sortsthespecifiedlistaccordingtotheorderinducedbythespecified
comparator.Allelementsinthelistmustbemutuallycomparable.
DoesanythingbotheryouaboutCollections.sort()?
JCFproblems
• WherearealltheiteraFonpaWerns?
•  java.util.Collectionsprovidesmethodsforsort(),min(),max()and
justafewothers.
• ThemostcommoniteraFonpaWernsaremissing:
• Collectalistofeachperson’sfirstname.
• Selectonlythosepeoplewhoselastnameis“Smith”.
8
ITERATIONPATTERNS
Javadoc
• 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
ITERATIONPATTERNS
Itera+onPaLerns
• CollectpaWern(akamaportransform).
• ReturnsanewcollecFonwhereeachelementhasbeentransformed
• e.g.collecteachpet’sname.
• Functionisthetypethattakesanobjectandreturnsanobjectofa
differenttype
• akaTransformer
JCFExample
List<Pet>pets=...
List<String>petNames=newArrayList<String>();
for(Petpet:pets)
{
petNames.add(pet.getName());
}
10
COLLECTPATTERN
Itera+onPaLern
•  Functionisthetypethattakesanobjectandreturnsanothertype.
EclipseCollec+onsExample(AnonymousInnerClassSyntax)
MutableList<Pet>pets=...
MutableList<String>petNames=pets.collect(
newFunction<Pet,String>()
{
publicStringvalueOf(Petpet)
{
returnpet.getName();
}
});
11
COLLECTPATTERN
Itera+onPaLern
•  Functionisthetypethattakesanobjectandreturnsanothertype.
EclipseCollec+onsExample(Java8)
MutableList<Pet>pets=...
MutableList<String>petNames=
pets.collect(pet->pet.getName());
MutableList<String>petNames=
pets.collect(Pet::getName);
12
COLLECTPATTERN
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
SELECTPATTERN
Itera+onPaLern
Collect
ReturnsanewcollecFonwhereeachelementhasbeen
transformed.
Select
ReturnstheelementsofacollecFonthatsaFsfysome
condiFon.
CodeBlocks
•  sortThis()takesaComparator,whichisastrategyinterface.
• Similarly,collect()andselect()take“codeblock”parameters.
•  collect()takesaFunction.
•  select()takesaPredicate.
• Don’tgethunguponthesenamesbecausetheIDEwillremindyou.
15
ITERATIONPATTERNS
Examples
K ATA I NTRODUCTION 16
• EclipseCollecFonsMiniKatausesPerson,Pet,PetType
• Dataisavailabletoyouthroughthis.peoplewhichhassomeperson
andpetobjectssetforyou
17
KATAINTRODUCTION
Domain
KATAINTRODUCTION
Domain
18
K ATA E XERCISE 1
19
• FixExercise1Test;theyhavefailures.
• Figureouthowtogettheteststopassusingwhatyouhaveseensofar.
• Shouldtakeabout15minutes.
20
KATA
Exercise1
T ESTUTILS 21
• EclipseCollecFonsdistribuFonincludeseclipse-collec+ons-testu+ls.jar.
• IncludeshelpfuluFlityforwriFngunittests.
• CollecFon-specific.
• ImplementedasanextensionofJUnit.
• BeWererrormessages
• MostimportantclassiscalledVerify.
CodeExample
ExamplefromtheprevioussoluFon
Verify.assertSize(2,peopleWithCats);
Insteadof
Assert.assertEquals(2,peopleWithCats.size());
22
TESTUTILS
Verify
F LAT C OLLECT P ATTERN 23
• flatCollect()isaspecialcaseofcollect().
• Withcollect(),whentheFunctionreturnsacollecFon,theresultisa
collecFonofcollecFons.
CodeExample
MutableList<Person>people=...;
Function<Person,Iterable<PetType>>function=
person->person.getPetTypes();
MutableList<MutableList<PetType>>pets=
people.collect(function);
24
FLATCOLLECTPATTERN
Backgroundoncollect()
• flatCollect()outputsasingle“flaWened”collecFoninsteadofa
collecFonofcollecFons.
• ThesignatureofflatCollect()issimilartocollect(),exceptthatthe
FunctionparametermustmaptoanIterabletype.
flatCollect(Function<?superT,?extendsIterable<V>>function);
CodeExample
MutableList<Person>people=...;
MutableList<PetType>pets=
people.flatCollect(person->person.getPetTypes());
25
FLATCOLLECTPATTERN
flatCollect()
M ORE I TERATION P ATTERNS 26
Select
ReturnstheelementsofacollecFonthatsaFsfythe
Predicate.
Reject
ReturnstheelementsofacollecFonthatdonotsaFsfy
thePredicate.
ReturnsthenumberofelementsthatsaFsfythe
Predicate.
Count
Short-circuitpaLernsthatusePredicate
Detect
FindsthefirstelementthatsaFsfiesthePredicate.
AnySa+sfy
ReturnstrueifanyelementsaFsfiesthePredicate.
AllSa+sfy
ReturnstrueifallelementssaFsfythePredicate.
27
ITERATIONPATTERNS
OtherpaLernsthatusePredicate
Lists
•  MutableListextendsList.
•  FastListisadrop-inreplacement
forArrayList.
28
ITERATIONPATTERNS
InheritanceHierarchy
Sets
•  MutableSetextendsSet.
•  UnifiedSetisadropin
replacementforHashSet.
29
ITERATIONPATTERNS
InheritanceHierarchy
“W ITH ”M ETHODS 30
•  collectWith(),selectWith(),andrejectWith()arealternateformsof
collect(),select(),andreject().
• Originalformsalltakeasingleparameter,acodeblockwhichtakesa
singleparameter.
• Whatifwewanttofindgroupsofpeopleatdifferentages?
CodeExample
MutableList<Person>voters=people.select(
person->person.getAge()>18;
);
“WITH”METHODS
collectWith(),selectWith(),andrejectWith()
•  collectWith(),selectWith(),andrejectWith()arealternateformsof
collect(),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”METHODS
collectWith(),selectWith(),andrejectWith()
Howtheycanbeused
Theseareusefulwhenyouwanttousemethodreferencesratherthan
lambdas.
//doesnotcompile
MutableList<Person>peopleWithCatsLambda=
this.people.select(Person::hasPet(PetType.CAT));
33
“WITH”METHODS
ForalmosteverycommoniteraFonpaWern,thereisanequivalent“With”
method.
-  selectWith()
-  detectWith()
-  rejectWith()
-  anySatisfyWith()
…etc
Howtheycanbeused
Theseareusefulwhenyouwanttousemethodreferencesratherthan
lambdas.
MutableList<Person>peopleWithCatMethodReference=
this.people.selectWith(Person::hasPet,PetType.CAT);
34
“WITH”METHODS
ForalmosteverycommoniteraFonpaWern,thereisanequivalent“With”
method.
-  selectWith()
-  detectWith()
-  rejectWith()
-  anySatisfyWith()
…etc
K ATA E XERCISE 2
35
KATA
Exercise2
• FixExercise2Test.
• UsetheotheriteraFonpaWernsthattakeaPredicate.
• UsetheflatCollectpaWern
• Shouldtakeabout15minutes.
36
B AG 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
Methods
Inheritedfrom
select(),collect(),etc.
RichIterable
add(),remove(),iterator(),
etc.
MutableCollection
(java.util.Collection)
occurrencesOf(),
forEachWithOccurrences(),
toMapOfItemToCount()
Bag
addOccurrences(),
removeOccurrences()
MutableBag
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
M ULTIMAP 42
•  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
MULTIMAP
NewType
•  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
MULTIMAP
NewType
MULTIMAP
Before
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);
}
A\er
MutableListMultimap<String,Person>lastNamesToPeople=
people.groupBy(Person.TO_LAST_NAME);
MutableList<Person>smiths=
lastNamesToPeople.get("Smith");
45
MULTIMAP
Mul+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
MULTIMAP
Mul+map
• Whathappensifyouaddthesamekeyandvaluetwice?
• DependsonthetypeofthebackingcollecFon.
CodeExample
MutableListMultimap<String,Person>multimap=
FastListMultimap.newMultimap();
multimap.put("Smith",person);
multimap.put("Smith",person);
MutableList<Person>smiths=multimap.get("Smith");
2
Verify.assertIterableSize( ,smiths);
47
MULTIMAP
Mul+map
• Whathappensifyouaddthesamekeyandvaluetwice?
• DependsonthetypeofthebackingcollecFon.
CodeExample
MutableSetMultimap<String,Person>multimap=
UnifiedSetMultimap.newMultimap();
multimap.put("Smith",person);
multimap.put("Smith",person);
MutableSet<Person>smiths=multimap.get("Smith");
1
Verify.assertIterableSize( ,smiths);
48
• groupByEach()isaspecialcaseofgroupBy().
• Analogoustothedifferencebetweencollect()andflatCollect().
• AppropriatewhentheFunctionreturnsacollecFon.
• ThereturntypeisthesameasgroupBy().
CodeExample
MutableListMultimap<String,Person>lastNamesToPeople=
people.groupBy(LAST_NAME_FUNCTION);
MutableListMultimap<PetType,Person>petsToPeople=
people.groupByEach(PET_TYPE_FUNCTION);
49
MULTIMAP
groupByEach()
T ARGET C OLLECTIONS 50
TARGETCOLLECTIONS
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
•  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
TARGETCOLLECTIONS
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
TARGETCOLLECTIONS
Covariantreturntypes
K ATA E XERCISE 3
54
KATA
Exercise3
• FixExercise3Test.
• UseBag,MulFmap.
• Shouldtakeabout10minutes.
55
P RIMITIVE C OLLECTIONS 57
PRIMITIVECOLLECTIONS
EachdatastructurehasanequivalentprimiFveside.
EclipseCollecFonssupportsallprimiFves–int,double,short,long,
float,boolean,char,byte
MutableIntList
MutableIntCollecFon
MutableIntSet
MutableIntBag
PrimiFveIterable
IntIterable
LazyIntIterable
ImmutableIntList
ImmutableIntCollecFon
ImmutableIntSet
ImmutableIntBag
58
PRIMITIVECOLLECTIONS
ClassDiagram
ThereisalsothesamerichandfluentAPIthatthenonprimiFvesideoffers.
Examples
MutableIntListintListOfAges=
this.people.flatCollect(Person::getPets)
.collectInt(Pet::getAge);
MutableIntListselection=
intListOfAges.select(age->age>2);
MutableIntSetintSetOfAges=intListOfAges.toSet();
59
PRIMITIVECOLLECTIONS
Primi+veAPI
K ATA E XERCISE 4
60
KATA
Exercise4
• FixExercise4Test.
• RefactorJava8streamstoEclipseCollecFons.
• Shouldtakeabout20minutes.
61
K ATA E XERCISE 5
62
KATA
Exercise4
• FixExercise5Test.
• Thisisextra-credit
• Usetargetversions,methodsonRichIterable
• Shouldtakeabout20minutes.
63
A PPENDIX 64
A NONYMOUS I NNER C LASS 65
• Aninnerclasswithnoname.
• Lookslikeanormalconstructorcall,butitworksonabstracttypes
(includinginterfaces).
• Hasabodyarerwardswhichmakesthetypeconcreteoroverrides
methoddefiniFons.
• Hasarandom-lookingclassnamearercompilaFon.
•  OuterClass$1forthefirstanonymousinnerclassinOuterClass.
CodeExample
Comparator<Person>comparator=newComparator<Person>()
{
publicintcompare(Persono1,Persono2)
{
returno1.getLastName().compareTo(o2.getLastName());
}
};
System.out.println(comparator.getClass());
66
ANONYMOUSINNERCLASS
Defini+on
C LOSURE 67
WikipediadefiniFon:
“[A]closureisafirst-classfuncFonwithfreevariablesthatare
boundinthelexicalenvironment.
“SuchafuncFonissaidtobe‘closedover’itsfreevariables.
“Aclosureisdefinedwithinthescopeofitsfreevariables,andthe
extentofthosevariablesisatleastaslongasthelifeFmeofthe
closureitself.”
•  Javadoesnothaveclosures.
•  Java8haslambdas.
68
CLOSURE
ClosureDefini+on
CLOSURE
ClosureDefini+on
Javadoesnothaveclosures.
Inthecodeexample,thePredicateisaclasswithaStringfield.
Itisnotthesamecopyasthemethodparameter.
CodeExample
publicCustomergetCustomerNamed(Stringname)
{
Predicate<Customer>customerNamed=
Predicates.attributeEqual(Customer.TO_NAME,name);
returnthis.customers.detect(customerNamed);
}
69
CLOSURE
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
Javadoesnothaveclosures.
Inthecodeexample,thePredicateisaclasswithaStringfield.
Itisnotthesamecopyasthemethodparameter.
•  IfyouuseananonymousinnerclasstoimplementthePredicate,you
havetomakenamefinalinordertosaFsfythecompiler.
CodeExample
publicCustomergetCustomerNamed(finalStringname){
Predicate<Customer>attributeEqual=
newPredicate<Customer>(){
publicbooleanaccept(Customercustomer){
returncustomer.getName().equals(name);
}
};
returnthis.customers.detect(attributeEqual);
71
}
CLOSURE
ClosureDefini+on
Javadoesnothaveclosures.
Inthecodeexample,thePredicateisaclasswithaStringfield.
Itisnotthesamecopyasthemethodparameter.
•  IfyouuseananonymousinnerclasstoimplementthePredicate,you
havetomakenamefinalinordertosaFsfythecompiler.
•  Refactortheanonymousinnerclasstoanamedinnerclassandyoucan
seewhy.
CodeExample
privatestaticfinalclassCustomerNamedimplements
Predicate<Customer>{
privatefinalStringname;
privateCustomerNamed(Stringname){
this.name=name;
}
publicbooleanaccept(Customercustomer){
returncustomer.getName().equals(this.name);
}
}
72
CLOSURE
ClosureDefini+on
B LOCKS 73
BLOCKS
UML
74
BLOCKS
Func+on
Functiontransformsonetype(T)toanother(V):
publicinterfaceFunction<T,V>
extendsSerializable
{
VvalueOf(Tobject);
}
Usedin:
•  collect
• flatCollect
•  groupBy
•  minBy
•  maxBy
•  toSortedListBy
•  sortThisBy
•  toMap
75
Predicatetakesanobjectofsometype(T)andreturnsaboolean:
publicinterfacePredicate<T>
extendsSerializable
{
booleanaccept(finalTeach);
}
Usedin:
•  select
•  reject
•  detect
•  count
•  anySatisfy
•  allSatisfy
76
BLOCKS
Predicate
Proceduretakesanobjectofsometype(T)anddoesn’treturnanything:
publicinterfaceProcedure<T>
extendsSerializable
{
voidvalue(finalTeach);
}
Usedin:
•  forEach
77
BLOCKS
Predicate
R ICH I TERABLE 78
collect
TransformselementsusingaFunctionintoanew
collecFon.
flatCollect TransformsandflaWenstheelementsusingaFunction.
groupBy
GetsakeyforeachelementusingaFunctionandputs
thekeyandelementintoaMultimap.
79
RICHITERABLE
CheatSheet
sortThisBy
GetssomeaWributefromeachelementusinga
Functionandsortsthelistbythenaturalorderofthat
aWribute.
toSortedListBy GetssomeaWributefromeachelementusinga
Functionandreturnsanewlistsortedbythenatural
orderofthataWribute.
minBy
GetssomeaWributefromeachelementandreturnsthe
elementwhoseaWributeisminimal.
maxBy
GetssomeaWributefromeachelementandreturnsthe
elementwhoseaWributeismaximal.
toMap
Getsakeyandvalueforeachelementusingtwo
Functionsandreturnsanewmapcontainingallthe
key/valuepairs.
80
RICHITERABLE
CheatSheet
select
ReturnstheelementsofacollecFonthatsaFsfysome
condiFon(Predicate).
reject
ReturnstheelementsofacollecFonthatdonotsaFsfythe
Predicate.
detect
FindsthefirstelementthatsaFsfiesthePredicate.
count
ReturnsthenumberofelementsthatsaFsfythe
Predicate.
anySatisfy
ReturnstrueifanyelementsaFsfiesthePredicate.
allSatisfy
ReturnstrueifallelementssaFsfythePredicate.
forEach
ExecutestheProcedureoneachelement,doesn'treturn
anything.
81
RICHITERABLE
CheatSheet
min
Returnstheminimumelementusingeitherthenatural
orderoraComparator.
max
Returnsthemaximumelementusingeitherthenatural
orderoraComparator.
toSortedList Returnsanewlist,sortedusingeitherthenaturalorderor
aComparator.
makeString
ConvertsthecollecFontoastringusingopFonalstart,end,
andseparatorstrings.
appendString ConvertsthecollecFontoastringandappendsittoan
Appendable.
zip
TakesasecondRichIterableandpairsupallthe
elements.IfoneofthetwoRichIterablesislongerthan
theother,itsremainingelementsareignored.
zipWithIndex ZipsthecollecFonwiththeIntegerindexes0ton-1.
chunk
SplitsacollecFonintofixedsizechunks.Thefinalchunk
willbesmallerifthecollecFondoesn'tdivideevenly.
82
RICHITERABLE
CheatSheet
RICHITERABLE
InheritanceHierarchy
83
BAG
ClassDiagram
MutableList
MutableCollecFon
MutableSet
MutableBag
Iterable
RichIterable
ImmutableList
ImmutableCollecFon
ImmutableSet
ImmutableBag
84
BAG
ClassDiagram
HashBag
RichIterable
MutableBag
SynchronizedBag
ImmutableBag
UnmodifiableBag
Bag
85
MutableListMulFmap
MutableMulFmap
MutableSetMulFmap
MutableBagMulFmap
MulFmap
ImmutableListMulFmap
ImmutableMulFmap
ImmutableSetMulFmap
ImmutableBagMulFmap
86
MULTIMAP
ClassDiagram
O PTIMIZATION 87
•  collectWith(),selectWith(),andrejectWith()arealternateformsof
collect(),select(),andreject().
• Originalformsalltakeasingleparameter,acodeblockwhichtakesa
singleparameter.
• Whatifwewanttofindgroupsofpeopleatdifferentages?
CodeExample
MutableList<Person>voters=people.select(
person->person.getAge()>18;
);
88
OPTIMIZATION
collectWith(),selectWith(),andrejectWith()
•  collectWith(),selectWith(),andrejectWith()arealternateformsof
collect(),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
OPTIMIZATION
collectWith(),selectWith(),andrejectWith()
–DonaldKnuth
90
OPTIMIZATION
“Weshouldforgetaboutsmall
efficiencies,sayabout97%ofthe
Fme:prematureopFmizaFonisthe
rootofallevil”
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.