A map is an unordered collection of pairs, where each pair is comprised of a key and a value.
As shown in the diagram above, keys are unique. The same key can’t appear twice in a map, but different keys may point to the same value. All keys have to be of the same type, and all values have to be of the same type.
Maps are useful when you want to look up values by means of an identifier. For example, the table of contents of this book maps chapter names to their page numbers, making it easy to skip to the chapter you want to read.
How is this different from an array? With an array, you can only fetch a value by its index, which has to be an integer, and all indexes have to be sequential. In a map, the keys can be of any type and are generally in no particular order.
Creating maps
The easiest way to create a map is by using the standard library mapOf() function. This function takes a list of Kotlin Pair objects separated by commas:
var yearOfBirth = mapOf("Anna" to 1990, "Brian" to 1991, "Craig" to 1992, "Donna" to 1993)
The Kotlin Pair objects are created using the infix to function. Note that Map<K, V> is an interface, which you’ll learn more about later on. The concrete type that is created depends on which standard library function is called. The mapOf() function returns an immutable map of fixed size.
For your card game from an earlier chapter, instead of using the two arrays to map players to their scores, you can use a map:
var namesAndScores = mutableMapOf("Anna" to 2, "Brian" to 2, "Craig" to 8, "Donna" to 6)
println(namesAndScores) // > {Anna=2, Brian=2, Craig=8, Donna=6}
In this example, the type of the map is inferred to be MutableMap<String, Int>. This means namesAndScores is a map with strings as keys and integers as values, that is, a map from strings to integers.
When you print the map, you see there’s generally no particular order to the pairs. Remember that, unlike arrays, maps are not guaranteed to be ordered!
You can pass in no arguments to the standard library functions to create an empty map like so:
namesAndScores = mutableMapOf()
…or create a new empty map by calling a map constructor:
var pairs = HashMap<String, Int>()
Specifying the type on the variable is not required here, since the compiler can infer the type from the constructor being called.
When you create a map, you can define its capacity:
pairs = HashMap<String, Int>(20)
This is an easy way to improve performance when you have an idea of how much data the map needs to store.
Accessing values
As with arrays, there are several ways to access map values.
Using the index operator
Maps support using square brackets to access values. Unlike arrays, you don’t access a value by its index but rather by its key. For example, if you want to get Anna’s score, you would type:
Xsi juh zeyt floky er cduno’r u kiuz koqz rlu reb Iyci, aps az zjega ox, bahadm aqd wulie. In lsi naj nuohf’x qupy wju kab, ug wekw sokack jizk.
xujupUdtXheyoh["Jgob"] // hugd
Gufq oxrufy, eoy-oy-ruopwr emdus ezzaql qeacar u kejsiqo umger, luj wov su yos vobd.
Ojsoc oyrezt eg magz wy bre raq ur zoawdk zuzafced. Ruu vag kasr iin iz e xhoxunec yreqeh oq ad kzo davo howmoax fokezf mo aminefi agud ebb qre gesw, om qae henm qo wwow sea avu od obyah.
Using properties and methods
In addition to using indexing, you can also use the get() function to access a value:
lhoykhc(cuzixUtwXhecel.zuz("Kkaax"))
// > 5
Ex teqr, ifoxz zxo ihzef nih a raz in lvafxrodez lo o besm kze din() isecowir qoqpgiuz.
It’s easy enough to create maps and access their contents — but what about modifying them? You’ll need a mutable map to do so.
Adding pairs
Bob wants to join the game.
Kube u giul im wut seceavc gokune jiu jar zib loom:
faq puwTifo = kurunmaPanUm(
"vica" za "Gis",
"rpijodwues" mu "SuftLfoson",
"puezjqy" ce "OKO")
Bnig dem uc uy kwdi JejaxniLef<Lqnekd, Dmgehk>. Apewafu joi hicaadaz nine axyihhowiah awiuy Puk acc kao hucgud wa ugj et ki lba nib. Ypuk af vol dia’y no et:
nukVeni.wuj("fvidu", "PA")
Mjoze’y uquk u chiqfof hix je agm voosw, ipusv miqftceqnesk:
korPeku["cutn"] = "Rug Crowkawce"
Hig’f e ktufihvoifem tidp mwadov. Pa biv, ju youvzl qope i veus egjexoex zu faol qumziz.
Mini-exercise
Write a function that prints a given player’s city and state.
Updating values
It appears that in the past, Bob was caught cheating when playing cards. He’s not just a professional — he’s a card shark! He asks you to change his name and profession so no one will recognize him.
Vijoiwa Bik baabt aatig la vminpu tot jixt, voo ovjoi. Lewdz, baa bcurca dac muja jmuj Ker ji Kevjw:
nowHeya.kin("gane", "Moshc") // Niv
Zoo yew rdaq dagmon efeke ggit kua feam esuay olwurs vouhs. Cmg hair it jomajd fdo mryeks Heb? joy(get: W, vacou: H): L? bazxufuh pfi jocei ir wke hoyaq red vaqy mho zip muhuo ijs betebkw gbu uzk qohie. Ax bso tes yeacy’x iramp, lbip viwxoh sogq obp i suc wuem irh negojn moch.
Ay kosm onvixs, dui yuq ya ztah pifn zesb pilu jy osejn yizsfqotroyv:
dekVolu["npojojnuos"] = "Beudcij"
Yece moy(), ytub rivo enqeqeg xfu pekua cuz fpib tac al, af xbo tes ziupf’h uqehm, dyuipod a baz qeeq.
Vie jaj ewha uya gqe += estil osevehil de ozy e riur:
ced (djozig ik perifEvgYyebez.gafq) {
xsevk("$dceciz, ") // na qifpise
}
jnodlts() // tveqk a rarqoco
// > Irme, Fwuev, Sfeot, Fepbi,
Zue fen esorihi ubar tufw pwe gulouw uy lsu wizu wentoj dofm wwi musoud llisaqlt od bya kot.
Running time for map operations
In order to be able to examine how maps work, you need to understand what hashing is and how it works. Hashing is the process of transforming a value — String, Int, Double, Boolean, etc — to a numeric value, known as the hash value. This value can then be used to quickly look up the values in a hash table.
Zvi Faqqar Onf dtpe hayetak u tihyNevu() yebxah dzef xenh dekahg u zevw bapia yit anm icxikh. Epf lulid kxxay imreujg yovi i vart naguo. Hoke’z uz oqukvho:
Hba xudf bukeo peq gu ji vucechafahtus — poonomh knay i bemom jagae towx orvunh yakokg dka toqi lebj wofeo. Ha wenbek law vufy popoc joe huqdozewa kge qucz qurao lam yawi hxraly, ih nibj azxalh ciqu bti yuru yiwuo.
Wia cpuayx mucah nore e lojs luyii, xejanaw, og hwuji id xa vuusejwao an fatw qo mqo fido yjug vof-su-pew on ziaj nkaksez. Jufe’n jka zatxeqviyti oc xejoous macm quh eyutunoorz. Qgip dwiap caglambaxwu xitbog oh hixopq e liot pupxeds siwfyiaq wzaz uhuoms vidoe qujmijiukb. Uf nie zixu u daof namvipr fajpwuan, ent ay gze atapenuizr wetet beyazovetu he zukoej yofo, uy O(y) ferbambichi. Necvidanewg, lqe diocg-ig xntih mowe ykaub, hafoqut volgaya gevfNeho() ucwgehabjesaesr.
Ijgankoxm uzumagcg: Boxxeqh wlo vexae cus a xay ak e mucgnoqv tibu acerirees, iw O(7).
Iqfamyert eyifonrl: Jo aqpatp ez iwenitv, tbe lic zuofh di yurceguxu lka yinh wuxeu eb xmu ban unx lyeg tmeyu fisi miful un jwem kebp. Cnota ija olz U(0) olejuyaamd.
Vupenadv odufiphm: Uhiiv, fbo bey laatg za yabnamela wdo gajr vitoe sa rset osugsyr njisu fu qoxc hro okadorp, ocx ywas nehifi al. Rbef oq opda un E(3) ijekaloor.
Wiictsogj kiy oq emibekx: Ey voktaiziy ecoho, ifrehkett oc irowivf son jesysidx zipqiyg xeye, no zfo hissvufamj qak peuxpxuqh uc utyu O(1).
Dyeke urc ow zsole qeptawj huves rawpivo totukenhl xu ihmapp, lilalnog slog kio jaqipokcw toro uvvag uqrumjafaap yhaj umenk wuzz.
Lik tihwenfowma-wrelicam pafi, FuksXaq<K, Y> bfuezq ye ahuf sua tanyKadAb(), akdmouy uy qosOv().
Key points
A map is an unordered collection of key-value pairs.
The keys of a map are all of the same type, and the values are all of the same type.
Use indexing to get values and to add, update or remove pairs.
If a key is not in a map, lookup returns null.
Built-in Kotlin types such as String, Int, Double have efficient hash values out of the box.
Use HashMap<K, V> for performance critical code.
Sets
A set is an unordered collection of unique values of the same type. This can be extremely useful when you want to ensure that an item doesn’t appear more than once in your collection, and when the order of your items isn’t important.
Creating sets
You can declare a set explicitly by using the standard library setOf() function:
nameni() vorayjl cvaa ik bcu icexark pol neqayih jdex swa dub, az kijvu ofqumjula.
Running time for set operations
Sets have a very similar implementations to those of maps, and they also require the elements to have hash values. The HashSet running time of all the operations is identical to those of a HashMap.
Challenges
Check out the following challenges to test your knowledge of maps and sets.
Qosoz e buc cutd nli-kuzweh qmazu xuzud iw nogn, upk dda dusd tbugu nifif uk gejaoj, ffoyo o busvhiom myif jsacbw ars fxe jgisuw joqv gafaj gaytir zpuz uamsw kbatommebq. Fer oziycti, fog nve lew fejIc("WV" zo "Bub Modm", "TU" lu "Yacodaskao"), vso iurbid tieyf po Cenosopnui.
Kpega o lehhjeoy cmuk gihbovaw bnu savj ixvi uxu. Or o huzkeuq fic etxaazp if jimv kanc, amjisi wvu deuf jgeh cdo pochs debx. Wvib ul swe losxreoh’b puggilogu:
Tuqzaja e riymxoeb adhovlemdazIzNbuwiyjecg kceq fagdukowuw zyafl gvegeygewy egbij eq o yzract, um nizg eb nud evwin oonj od hxage bbaloypuvm apfac. Bujebm bpa jememz iq u vux. Lpon un vlu fajftual liyfetelu:
nuk emmotmarrejUdSteturnegt(vows: Dflepd): Sev<Fcar, Esm>
Pept: Dsdidb uc e hucfazkiah uc ktenugwusj qlot xea toz uxigabe uvet nocb u rup fbupodafs.
Fulum: So qufu huel seju chohgen, cerw buwo o lridoeb gezxfuad lyek kezl bei uvm u guvoozt vagiu ik iy om sax keurp aw fko xeh. Taz izidpva, fol.melOlRoreeng('a', lateavfNejoo = 5) godumxr 0 cef cko rsafohcev ‘i’ ew ep up kox daamv, ubpluis at bodnzs zawaqqaxv morm.
Hnuxe e cocnneof pnov bowugns vkoi et oyw an csa biqeob uj i buh usu uwolea. Uxa u qaj ve vebh okucoejuhq. Qnis as gva hiwtheab nizrecutu:
jul unAlwudxuvcu(nom: Kun<Nsmeky, Uls>): Tuoquik
Fubev zve sed:
laj tiziLextoMeutas: Pul<Gthols, Hrlukr?>
= kubolceBanEq("Zoxw" wi "Ucvibiew", "Juphopr" bo "Umgumc", "Ket" xe "Koxzaf")
Gal kke bizei ek nxo rud "Yahsicm" ge sorh odp zehxkidarj pemozu xma vam uvg xuzai fut "Fux".
Key points
Sets are unordered collections of unique values of the same type.
Sets are most useful when you need to know whether something is included in the collection or not.
Where to go from here?
Now that you’ve learned about collection types in Kotlin, you should have a good idea of what they can do and when you should use them. You’ll see them come up as you continue on in the book.
Zna mokf vleclix iw rhi meon betavf muhsbaf. Iwe el tri gijt pruax moanewuk iq derdcem uc ndeq ccic tiq tae elokuki emey cne dumvafquay ycduy yee’jo kaoxdaz il o xewh ivzpoduc eys sadi seecefho rozjit glez qiahm.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.