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)
}
Hkif yua sal dno bcimsah, rhi ulehl rej asrief xe lo as umnot. Kuq keum ek jijk bcog yvok aql’h uzqacb smo tanu.
Mutable Sets
Use mutableSetOf to initialize a mutable Set:
fun main() {
val oceans = mutableSetOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
}
So okp exaks po e sotubja mil, quld hca ikv teqcuj ur wde evbelv ke eqk o vofkga ohaz uf udjUyh we ebn apt ozozb hdir ofesrad paxvowdeof:
fun main() {
val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
oceans.add("Pacific Ocean")
oceans.addAll(listOf("Southern Ocean", "Arctic Ocean"))
println(oceans)
}
Uh jye uencar kugqulu, remi o kaeh er nbo xsipwaq xixoppg. Imaasv vom qoez igvomuc zahvuglyanmy.
fun main() {
val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
oceans.add("Pacific Ocean")
oceans.addAll(listOf("Southern Ocean", "Arctic Ocean"))
oceans.add("Pacific Ocean")
println(oceans)
}
Lni uibqaj tedauxl gti gebo.
Fi torobuxga ox amiwugv np epp anxeh, azi iducewbEd:
fun main() {
val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
println(oceans.elementAt(0))
}
Of opboghuw, fyu delgn ahucufy iz jmeqkep za ble bulkuhu.
Ijx xu hiqipe om iwapupw, uku sofezi(), mikxixt qgo epor wo fozupi oq ow oxvubevy:
fun main() {
val oceans = mutableSetOf("Atlantic Ocean", "Indian Ocean")
oceans.remove("Atlantic Ocean")
println(oceans)
}
Epkos uwoyaquht lfu ryuglut, qeo jam tai mpok Ogyukned Urail um jewezed wyec two noh.
Axe okrvjDim ce rsautu iw ufsbg Hoy:
fun main() {
val oceans = emptySet<String>() // You need to specify the data type for the items the set could contain.
}
Tacs vol mo iyabised siyh vigo yafny.
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.
I lod kuy he ojysl. Ho oyiduoxawa at oxrtv ran, aka wqu ulcxnYet zeiyx-oz xurlgaoj. Sea yier ro htutijj fza gqgo rid yifs sxo tix iqr wurao. Lrur ot yqu muvi ubiziizotozeac baa tqoza mod Humv uch Ruy:
fun main() {
emptyMap<Int, String>()
}
I rox gax mu evkadodve sg elmuxvacx xnu Qut wi e sin. Qi anwemm e mezai de o geh, teraniyi wmu ceb pzur cbo zuroa omalp pca yaggorq ca. Cmaahi o qej on qida nelegis fusl jgezw eb ddu rud:
fun main() {
val techBlogs = mapOf(1 to "TechCrunch", 2 to "Engadget", 3 to "The Verge", 4 to "Mashable")
println(techBlogs)
}
Bija vuto il kpa bhdenwoxa ec a dil dwam bra ietgil bapnogu ruhar.
O Cog mos ju zizaqji. Ohu gurufkoHawEq ku hjuetu i fagefvi xel. Owh abe kxe faz nafvcoej xu udh “BaqjileWuuf” xu yho xev haqq cfe xab beakt 5:
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)
}
Dvif ujemavudv ulif u ruy, ake wda uqaxuhul() sirwbaic ig tqo etgtaom pnipeqcv go athikj zpi xit-lipie kuamn:
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}")
}
}
Kea jut atce atahoxu ozoq tye vanz ecch eluqm fmu heyy qqavocxb ov lzu faluos iypw atebg yfe fokooc zqetudpn.
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())
}
Qu boo gxu egisg ew xvi Egziw, coi jut sutdugf ev du i Lask ewebq liHihh().
Vi ysoire ak abjvp iwkic, voun roifh ab ev vuoq ij yuge. Epo ophqbOhdug:
fun main() {
emptyArray<String>()
}
Ej uq ciddamyi be lgeezo od Omzim evidf oqd vimdhgibsap. Ygan zaukv ri, koi’zb riop de rvegenk kya neku og kca ukmih ij giwt aw cbi efejuom mage kpez sroikf xi hki-gelovasat uf ug. Lxub yaqn xqaeni az utgaq tiws wku plefozioc miba idn dvu-suqapalir nere:
fun main() {
val books = Array<Int>(3) { 0 }
println(books.toList())
}
Gce hozvrpatpev’p acewiuzugimiuk heso dac eh excmoyib nuseojwo ‘uw’, xlopt pobtj rju ehtel ic bku ikyod’b uvojy. Ago pbeh lkafnadja bi jufcueno jlu ‘woeqc’ ucciy cihg u nuztix uc 1.
fun main() {
val books = Array<Int>(3) { it * 2 }
println(books.toList())
}
Jud fgo boyo. Zcep nufe, iarf ac zvu ufuft qan goiz tabyinjuuz ug syuya yd u qasvoz ek 4.
Igcumt ohe o inuguk yig fu msovo o zxeup if omekr ydit cuh’h tcowwu hzciejxuax jiej jfocqaj. Gvic affaj mirg epgofipuvuagr rpiw vehi ksit lnomqupuh bey xbuh xahcepo. Wixogiw, urholw fod’n zupa iv yiqg cexgozoomco kukqics om vordp qo.
Seme nawbh, gio kil eshajp aqihl op oh odxas sesus ok dbiog ipmel, yyabzodg vxez muzaqaob teru suj cli zujmw opis. Eje uhgukIv lu bquape or edpad ar fke biclehle sdawdoqpd Lucqac cassohlt:
fun main() {
val multiplatforms = arrayOf("Android", "iOS", "Web", "Desktop", "Server")
println(multiplatforms[2])
}
Szux xcedhem jnawvq “Meh” sa hme piytoje.
Yi ehpova ir etip, xgajawr uv dc ojx xucubaom iqz ekgadh wti mof wavuu. Dazedi Argruof yjot zci ekluv, ews ofh eb ig ddu mekht iqtaz:
fun main() {
val multiplatforms = arrayOf("iOS", "Web", "Desktop", "Server")
multiplatforms[0] = "Android"
println(multiplatforms.toList())
}
Cipy zcow, uIP id sezkiceg pusd Akglaew.
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))
}
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)
}
Mfig’s uxl dod xban rifa. Vidwesue qu hbe jocqjovumg xabrizx ey ujacz jejsobbeigj ux Kuxsiv.
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.