91
Eclipse Collec+ons and Java 8 Lambdas Mini Code Kata Basic Ideas, Basic Implementa+ons March 2016 Copyright © 2016 Goldman Sachs. All rights reserved.

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:

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

“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:

“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:

“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:

“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:

“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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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.