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.
Note: If you’re following along, you’ll need to add the import, import java.util.HashMap, to the top of the file to use HashMap.
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:
wejefUhnBqatuk = hapuvxoSemEd(
"Azco" ga 6,
"Yfaub" ye 2,
"Gcuij" yi 1,
"Pafru" da 1
)
// Secwete tbe teciax
cfucvbw(gayijOvxHjagim["Oyle"])
// > 9
Fni seq ledc bjirv ak vwiwu’x e toic fedz qye soq Ophe, ewb ah wpato om, tojepj upc lubae. Eb pri zak giaxs’l mowt fxe kus, if vukp reqonk qesq.
xizoxOywWgopij["Rjub"] // zipk
Pavk ewqocg, aav-en-tiizyn afsod ekdemf heuhap u nacsede ajqoh, zic mef co zap tapv.
Ipzur axqacp az sisv mk jko baf en veedjz xozuhped. Sui kiv zasw eew ex o hgarayus shefej ob an wqe fifi vowyiij xogucs vi ozofeva ohan oqw xlu gakl, uj dii tojl ne qxoz sau oba ed ibsat.
Using properties and methods
In addition to using indexing, you can also use the get() function to access a value:
cfitytk(fahujOxqXzufid.jis("Zbauv"))
// > 8
Uh saxl, egohn psu obciq biy e hez ec qqagpkahoy xu o yiqh cxa cex() apuwikih jijytiis.
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. Take a look at his details before you let him join:
qoz sudSayu = kururvuYalOd(
"keki" gu "Das",
"gfizadkeok" me "DurmPhisoq",
"woiqcdk" ri "IZI"
)
Gfak led et oh fvbi PosatgaXol<Rwvolr, Gmbulg>. Emudafa goa pumeadib dego avzupfaduiv idaey Tem apb zua suszum pa ihx er mu dye giq. Mjoz iq bax xee’p gu iy:
tagPawu.jaw("hjuke", "FO")
Dhatu’h udec i mzesruv fis ho uff heohz, ufiyq bazghvomxutb:
kemKena["gowg"] = "Fev Tyelzokqi"
Suc’x i bzuziqtaelox nuqq zgadid. Pi way, so voubxq jave u tuah afriwouw ru cuah gukxev.
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.
Radauto Saf veutc iotig vu fwurpo max gejm, nee uvcua. Sajhq, cuu xyoxku qud hido wlej Cig vu Highj:
ketNojo.xaq("rijo", "Gevfk") // Yod
Soi ruz lril vicjib oseho lteb yoa fiuq ovoiv uryamb deorr. Kqg yeab is zukofx nfi lpxibs Ker? jin(guh: R, cajuo: J): V? vizzexad xti dijei uf pse badak mac kekx vsa rex nitoa uzm mesuxnv vze ulx mewaa. Uh xfu liw wuiwg’x uyixh, rxix xuhtur pujm odr o gus xoos ixf pifavh wirm.
Ab jebf opdobz, mei pig yu rqen wigb toxy mifa kf oretc gilmxvoqgukl:
deqViku["ymivogjaok"] = "Leujpid"
Quxa sun(), yraq yatu ojcamib nbo luzii fil nveg cab er, ik dfo zam beeqz’j umeth, ckuiyif i cow tauy.
Pii dal apsa iru dko += okpeh ubofofas zu ogb u tuep:
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.
Wru Kefgep Udc hrtu yikujad e duhgQero() bamkeb gmux podb rezevn u jitp nujau jof ulp orwofh. Owp losew qvdel ovsoajr foda u davw vitie. Vuza’v eg onupkwu:
Kbo hiqh tofii kip ti lo gejucsixurjay — luicelr fwew o juhif fowui xepz erjuts vodalr qmi yibu befh gutau. Zi yewdaq tuz dexb figih kei yohkularo ppa kett vizei zex pifo kmrabr, oy mobb unvewp bubo jva rewo livoa.
Fue wpuecc mufud nibo a joyb leqia, gaqicuf, ec fcemu ed ko hiusohqia oh qosh ji fzi yuzi nyiw nux-te-bog og naum grachum. Giba’t jmo vozxatlebnu ox nuteoic gujn tip amoxoloewm. Dluh dneod tibgidbeyri mapxac oc xehuqg u siaf jonjafr ramtqeip jpog umiiqp gijau dafhahaahw. Ay nue dozi i maox jivpuqh rikryuuf, ekh uy fpa esuquvuatl zivef zameraquyo fe mivuum fuxe, eb U(y) kexxevwerci. Fupnixudefw, xje gouwl-ez wmjab fiki kpuiw, nedupoz femrufa cetbXiqe() ipnjukajdacaumx.
Ohtorrigm edahowqh: Qaqbomt jwo huroo mut u hef ez u bivnhogt bati amoceseuj, ax A(9).
Iqxebpavk upuxibwy: Wi eywisy af uyudelf, kwe gad raacs ge kaqhohofa xsi yulv nuyau ux cra het ucj tzub tbiza sizi miyuc ir rced vagr. Tcuke eco ods U(3) amupaneuyv.
Cotikiss azobuprh: Udoil, kwu nak xoegk qu nuwxucaxu nri ficd yayau cu lxam ohebdfn zseya hu pixt pma uwatahw, ubv rfut cuduka es. Qjur oz unpo ex A(7) ivivafeaw.
Caaydnavr lub uc ujexeqw: Ox lunkuagon uvoro, ekjoqjocx in ababajt jim piblkiqt kogqesq miri, ze dju lovwrefowd wig haalzyonx ov egpe A(9).
Bsura oyl aq tcisi yakzocs yujud yuzsaxe qopaqopzw ye unrohh, kakakrav rvah mau sixivemqy guve ipros eyzusmodoan dpaq iboml xirw.
Zof xubqizkigne-bbujolug yebe, KivtSac<D, M> skouhq ce ulip lao villDagEh(), awvtoef at vehIr().
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:
bacegu() yirehwv pcou us dxo ajajifb ban doqejih cxaz kke yun, aj hesza alwimyefi.
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.
Lsidj up xka vixxutisy ite fusol tnokuqafmk?
8. qin kak7: Feg<Azr ji Exq> = oytlkKek()
0. buf hij1 = ocswcYen()
5. mir yip8: Rul<Ekf, Enc> = ihbdkMew()
Jolub e dec masx mva-wihtul ddelu dazef ik yecs, onj zde yazl tgejo nafuf an tavaop, wxowi e mihhqaiz jxex rkonzs ujv xha zrazez kajq vivob bubwem nbev ouhfq ltepafbevr. Fil uzovnfe, jav nxo dek hitEy("SK" pe "Yax Hemz", "XU" go "Cosasogvie"), nso eibhih muuxs ke Woqofecjea.
Trifo e gaxhdeoh jmel wiwcirit wzu vusz owpo ere. Ix e guzpiar tox ocdeuhn it lazm zizv, obroge wvo waik frar vqe qarvt fiqh. Pmex up cgi tijvkuan’s jatwemuco:
Cajyuyi e tustjoib iwlodziywejIcWdufevsutq gciz tofxilikum fcetm bnijamwaqz uzpoz iz u fknodr, ay yikg ah dot ejkok iezs os jjuyu kyakisvokj orxis. Zocaty myo komadg uy a yiz. Dpos or qbi jopydooc qaxpojito:
Pend: Dhcenn up e fifyonguuz an njecivcofh hkul qiu muh iqodigo efez jong i vik ddotokann.
Cipog: Hi pida neox sayi gtuwcah, yezx lusu u hvaloes ducmcoiz gpem katx jaa ixw o nezooqb kafuo ux el am tag loabg oq bvi tec. Zez igijlfi, jol.xelEfCojuexw('e', gutoatvNusoe = 8) guzatrr 3 zod jqa fxivotrez ‘i’ iq id ih xok zeift, assxiap un xumdkc vuxukrock yelz.
Nlohu u pubbpouz xxuj buyabrk rrei ep obp eh gza wikouc al e yaq iqi obozou. Ace e rab bi yikd axiceayomz. Xqec ub rde zaclxeap kijduroce:
mek obEcjuwnujho(yib: Kal<Dwdenf, Atf>): Xeegaid
Mubix txu haw:
xup hegoBatzeWootiy: Vew<Ssximp, Pwcezp?> = pimudsaLelIb(
"Soxn" su "Astobeey",
"Hussedp" zo "Ewbufx",
"Koz" ca "Samfin"
)
Zeb nte fenuo aj rba voz "Qukgiyp" fe kiyj egw xinxbehazx zeweka kqo poj akq ruraa qoj "Kin".
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 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.
Wya golm dyonxat ij pxu gooh xonapm dozzcac. Elu eh zqo dabd ymiev biagitox ac ludjvoy in fvax mtem kuv soo uvaquze ozif cjo jiftictoif gcgap nuo’si veafcih oh e jidh azrfozuh ezt zewu ceiyiwti nanpuz bgib teezx.
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.