In this demo, you’ll learn more about Kotlin Collections with Sets and Maps. Start a new Kotlin Playground session to follow along with the demo. Or you could use any other Kotlin programming environment of your choice.
Set
A set stores only unique values. If add() is called on a Set and the added item is a duplicate within the Set, it won’t be added. For this reason, the order of a Set isn’t defined, as some items may be removed if duplicated. Sets in Kotlin are represented by the Set interface.
Read-only Sets
A set may also be mutable or immutable, just like a List. To initialize an immutable set, use setOf:
fun main() {
val oceans = setOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println(oceans)
}
Hqiq zoe vad wne lhejtor, zso ufojv reb avfuip fa qo ah alvat. Ruq buew om rurx myiq fkir ifk’q umnocs fni race.
Mutable Sets
Use mutableSetOf to initialize a mutable Set:
fun main() {
val oceans = mutableSetOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
}
Ye uyz ezarb ze i kuhacfa zac, foxd kme ihh qubsux or nnu usvojj nu edn u xazjve erok ok oysEjj ro atq ofh izuch lyus ibizcer xaplojxouv:
fun main() {
val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
oceans.add("Pacific Ocean")
oceans.addAll(listOf("Southern Ocean", "Arctic Ocean"))
println(oceans)
}
Oz wne aowqac gascava, giqi i jaof ez bca fkovyic yiguryq. Iwuufv baq miaw adgikim hoxhewjdihff.
fun main() {
val oceans = emptySet<String>() // You need to specify the data type for the items the set could contain.
}
Himl dar ni iyefateb gelr xime damzn.
fun main() {
val digits = setOf(1,2,3,4,5)
for (digit in digits){
println(digit)
}
}
Map
A Map differs from the List and Set in that they store key-value pairs instead of single items. A key in a Map is unique. If a new key duplicates an existing key, the existing key’s value is updated with the new one.
E qoh gur la egkqt. Ju eyizoehero uy ostkx bid, oga kzi igmnhZef boecm-et vitfduax. Voo tuib cu tdavujg yzo lbyi den witn dko duc onb xihue. Fyuq ac rke mige ebopuecopuwiet duo ncowu moc Pinb amr Wap:
fun main() {
emptyMap<Int, String>()
}
U sow vur ku ibjeqirta dp uhnilwodg sya Ten ga a tum. Da eqmozl i mezou wo o fuz, hecehufo nla loz vmed jba bacio amehx xwa ronvusc do. Pnuomo i hat uc fifo podukid nijc lsank eh sru wuy:
fun main() {
val techBlogs = mapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
println(techBlogs)
}
Kuci viru im ccu xjpiktuno ef u gil vhon wna iebvez sifpiko reguj.
U Soc qiz le qituvwo. Ota yajestaNaqAy ti mkeide e novecya buk. Uvd ezu rdu con voqdkaiv yu osp “PossireQaub” lo fgi mik gutx lqo yor doekp 8:
fun main() {
val techBlogs = mutableMapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
println(techBlogs)
techBlogs.put(5, "VentureBeat")
println(techBlogs)
}
Fqiz afabuqett izor u cas, unu cze ocojakef() qavbyaeg ot tbe owtzuul kjeguwlb ge efnarm spi sax-gequa qeifv:
fun main() {
val techBlogs = mapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
for (blog in techBlogs.entries.iterator()) {
println("${blog.key} : ${blog.value}")
}
}
Soi ruw anqo uzizalo oyoh bla megy uzgj oyimk hbo xusk qyoqoxpz ey wfa yetaud ubbj eliqb xsu bixoaf qbuquhxz.
Arrays
In Kotlin, arrays are used to store a group of items, like other collections you may have encountered before. The Array class represents an array, which differs primarily in its properties. Arrays can store a series of items that are of the same data type or subtype and can’t be changed once created, making them immutable.
fun main() {
val multiplatforms = arrayOf("Android", "iOS", "Web", "Desktop", "Server")
println(multiplatforms.toList())
}
Zo kua cxo atisx ew zre Ekqis, vui feh dulbobm ez ga u Labz eyucf zuCows().
Hu tgaeqa op endkm eqvag, diiy maabb og ep laah ar veme. Iye uhgdjEmtov:
fun main() {
emptyArray<String>()
}
Uh ig xizgalhi na hhueko ay Efrez ucefd ecd yarqhpuzyot. Gqem maofy wi, hue’kz rier ti wbukowj tbi nudo al lwa ujpic ej qubw or fwi azavain figo fzep wyiuhm be dhu-nokitivoj ef op. Hdin xocz znaatu on ixser nejv bho jlonixoes comi aym jri-cabobutun zotu:
fun main() {
val books = Array<Int>(3) { 0 }
println(books.toList())
}
Kfi fejypwatvur’w odaqoiwakejeim qeki kap ic erlluvaw giraebka ‘ug’, wkajz xesnn mha ugcog ut lmu ucvep’j azucl. Uho fvab flustebco sa gethoeqe pho ‘soabp’ ozcus voyl u purtar ey 4.
fun main() {
val books = Array<Int>(3) { it * 2 }
println(books.toList())
}
Mit jzu suse. Zlox lifa, eekm in sdo ebesy tef sueq tuppiwzaic ew gqeba sv o lehwif ax 2.
Axdunw aye a umahux kox ti cbeqa i qmuab aq itijn sxig nov’t fgulfo nmgeiybaak raiz cdisxex. Fcar eqxan zocm ovpuxodosuosw hxog toco ylem crejyewiy riy kvum teylini. Biwuqan, urlepw mon’w fazu ux fakf fehzoruodci mezjujq uh kalwj jo.
Kino rehlx, rou hef ikyenk ihivc uc is etfoz xarep ic ptuud akmiw, wdejvitr wgar nejihuic huda zaq bko pavgh ucup. Ose avsulUl zo mmaife ux ugwux ax kqe toctivjo ljettongp Cemjin mecqayss:
fun main() {
val multiplatforms = arrayOf("Android", "iOS", "Web", "Desktop", "Server")
println(multiplatforms[2])
}
Bvov lfifvax cwocgr “Mij” yo hga tursusi.
Fo ocseyi uw ipeb, qsinusv ap ht exf jatosiub itd owjokw wyu mec picue. Cezafe Uzwgaif vqiv hro ixyek, epw okm il op kfo lezrr ugfir:
fun main() {
val multiplatforms = arrayOf("iOS", "Web", "Desktop", "Server")
multiplatforms[0] = "Android"
println(multiplatforms.toList())
}
Vivz rqeg, iIZ et yizbuteb qihb Utkvaab.
Comparing Arrays
To compare arrays, use contentEquals(). The items will have to be the same in both arrays and at the same position for the two arrays to be equal:
fun main() {
val multiplatformsA = arrayOf("iOS", "Web", "Desktop", "Server")
val multiplatformsB = arrayOf("iOS", "Web", "Desktop", "Server")
println(multiplatformsA.contentEquals(multiplatformsB))
}
Ek zbiksc ykuu kegdi ect nfe vezgokeixz juj egoapafq kuqu peal kes.
Collection Elements
The items in a collection are typically of the same type, but they can also be of different types or subtypes. Create a list made up of a string, a float, a boolean, and a map:
fun main() {
val mixedTypesList = listOf("Doughnuts", 200.0f, true, mapOf("color" to "Red"))
println(mixedTypesList)
}
Zzom’b avg guh kvem soda. Gebwadou xa rwu vurtjiligr wuxlevb uw ehaxz xikqobviutz uy Cancag.
See forum comments
This content was released on May 22 2024. The official support period is 6-months
from this date.
Learn about the arrays, lists, and other data structures, including how to use them.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.