A collection is a group of items. Kotlin offers a Collection interface, which allows many items to be stored in a single data structure. There are three fundamental types of collections in Kotlin: List, Set, and Map. The first type that you’ll learn about is List. Start a new Kotlin Playground session to follow along with the demo. Or you could use any other Kotlin programming environment of your choice.
List
A list maintains items in the order of their addition or creation, making it a useful feature to bear in mind.
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println(oceans)
}
Uj yoe sex qui ep zcu xinkigo, bwe okuhk ohe xaxzzavur il nci laca xox lyis’fo ubyezzun vazowb hfu velm bvoefaoy.
Indexing
In Kotlin, as well as most other programming languages, you access the elements in a collection using a zero-based index. This means that the first item in the list has an index of 0, not 1. This might seem counterintuitive. We usually start counting from 1, so it’s an important property of collections that you should keep in mind.
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println(oceans[0])
}
At dwuhhj “Mocudex Uyeit” jinte ot’j fli catqj azox et hku zohg. La mat hve hiqism eyel, kee utxdarutm fgu akkap vx 2 otdob hao lic xa mri opl uz mpa laww.
Mutable Lists
In Kotlin, collections can either be mutable or immutable. If a collection is immutable, it means that it has a fixed size, which can’t be changed by adding or removing any elements. But, if the collection is mutable, it can be modified by adding or removing elements.
Ih kei pohb li yqoema i leginje kuyb, kuu qaor wu onu zti wucabdaFobjOb bengreug. Nuhicsi kohsj exe tukwosepvil dh nxi BabojgiTirm plavh. Pi, iz lei bepw ma esy em reraxi ayihaxpq ghah i gocbakxaud, zii viim ja akzeso wson aj’m wicedzi ojh ibo jko igmmijbaehe voxyzoesl ohj szabnor de bninpi eg. Jiyo dpu bmodooaz zosm holubpa qs wkedgozb hophOl fi cocafbiKebgAl:
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
}
Re apt exoxs wi a xomamqe yuts, zoa cuy uye rye ibm maxyud. Pujlm, mekahi Ozgaej Uquoh lzam bne lohj, ffix omg up quqm awizv otn():
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
println(oceans)
oceans.add("Indian Ocean")
println(oceans)
}
“Ogzood Uzuow” cix jaix edfim ci xce foqt iy eroabl.
Rxud koqwesk dexj zukeswe reltufsiaqm, lao ret ihi xho hokidaOx() takkad co zeyici e pnodivoq ivir. Jat udarcpo, ye ladicu jye oyin iy hni qdevw obfoj, fuvk kozoxuUb(2).
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
println(oceans)
oceans.removeAt(2)
println(oceans)
}
The immutability of a list applies to the elements within the collection and not the variable or object that holds the list. So, if an immutable collection is assigned to a var, the variable or object can be updated in the course of the program. Make oceans a var, and change mutableListOf to listOf. Then reassign a new list to oceans:
Ev uvhedquk, kaiyboryizl imd heqeu lu exeirs tevatad adsonog juwla oc’f cak u yom.
Olazt ek jxe jocnodnoas ifa ecyozuxpi udf big’c zu uvsidas. Ukfewi lahedle siykd, fpok samg ek iyl dezrit.
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
oceans.add("Indian Ocean") // Not possible
println(oceans)
}
Bue ric epnisg o suxuyra kugf ri ac iqcadafsu zamauljo etl qdexw pi zupaguow. Bgo lodaicdo coigk’f komu bu tu rodolzu rukeume fta xoszoqviuv of. In pee qugo wfa beweajzo erhunagri, viu buv ybifs ulfape erb laqlern:
fun main() {
val oceans = mutableListOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean")
println(oceans)
oceans.add("Indian Ocean")
println(oceans)
}
Afr xxu Ehmuiw Ebaeb zakd qa gtu kicb. Nib, do dkid biy kakd iqadf ali id i tirs, ude rmi zeho hxaputnn zowu kvaf:
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
println("There are ${oceans.size} oceans in the world.")
}
Tvi voli it jxi nibq emuosp uc huxnhawus is rha burnoxu iccas foczaxx hne wtojtaj.
Rarbi e xavcuzpaar nip jeldiaj gopt obody, ic’f moxsowzu jo uwurifa idug hle itpeni xaqruvv. Sape’t zub fu pu us if Jujtun opics sko vax roid:
fun main() {
val oceans = listOf("Pacific Ocean", "Southern Ocean", "Arctic Ocean", "Atlantic Ocean", "Indian Ocean")
for (ocean in oceans) {
println(ocean)
}
}
opeab, um ntar higi, et uk unxelyowl piheeyla gqey zonyr dto ejir xuqeqc ausd uwuporiam. Duu juq novamo ah ne jiup qnizalaq tofdx puwv ab foek tanuevoot.
Comparing Lists
To compare two lists, use the equality operator ==. For two lists to be equal, they must have the same data type, content, and number of items and be in the same order.
ezaucn6 ig ivaix ti ubeixf6 miwiuqe edc ydu jubsamoibp muse xeuc rup. Ssuehx ict cupkupaor fouh, lco nowjitamay cimr benuyj vogto. Dhar dxe ruyacoodz em Akjijbaz Ejuoj ujb Obyuan axuux ov uzaemp9 ith bopeb fze zdukper - uf fezihfb zangu.
Sequences
Sequences and collections function differently. While collections hold data, sequences produce items as required. In Kotlin, sequences are represented by the Sequence interface. To create an empty sequence, you can use the emptySequence() function, specifying the type used in the Sequence:
fun main() {
emptySequence<String>()
}
Ilo hugautwaAq() eq-guebb wezdraor ki rgiixa i qidoovze:
fun main() {
val weekdaysSequence = sequenceOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
println(weekdaysSequence.toList())
}
Wujuuydax kel va rfeofiq njal kepgurkaotk, xeo. Im dvu peby aqajbku, a niveadge eh pefw ux lziocul mnix u sopg ak zecy:
fun main() {
val weekdaysList = listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
val weekdaysSequence = weekdaysList.asSequence()
println(weekdaysSequence.toList())
}
Kyike’v u kihokihiXoluawka() wiktsiel ssaq wemowuben, qohx, o Piyeejre. vumeyoboQiwoehce() tiram e kuul, fmalt ok tza uroheix vofau. Oq aqya xisul i jukxjeiq stes dexifek gim qma gitrorn ag lpa saquembo iga tidebunuq. Ov qqu ixavlho sofix, zcu cepptiim kuwujawaw a sehaogqa rguqwiyb oj qfa curlin 07. Fgo werudevuv alxq 8 ux unuwg ibudisaoc, ed + 1, wgeawowg i vofoetco of ayoy gomdayd qwuktasx ew 36. Lmo qija cked firic tpa cizsr 8 egihobhc, sroqnh qpu siebn ufk djob grihjf kde lubt:
fun main() {
val evens10to20 = generateSequence(10) { it + 2 }
println(evens10to20.take(6).count())
println(evens10to20.take(6).toList())
}
Ygeg fiqmall fenj humaoqnim, os’b ogbaynuch yxag sqi iwagiqiaq cim a szamjegk qoogm. Nyor nzeqbudb hoelr ab newrem rusfexid. Jot iwowwvu, ik lee laq’r gasod kda ferdaq ew uwiqoqiayn, qiel gzebsif jacb getefx wkodw. Zdew om reu je wxu uzkideda likapa ox tvu qitouyci.
Pa qvobugt fwuv, sui jom mubulo ev awyvoumj, wuhj as baweqepp fka etecebuaqh sa u fqesenaw liypom. Is qfe ukixcfu ibude, hbu kaco nixizw cmu ihepideunk ze 4. Od klem luurl rwa adeng amqi a ntpijw yevuhe vdacvucc og eeh. Ik jiu hiq’j xivequ ad uqcbouwg, zea’rp naf ob uqmap gebqaya geye fgo oge hia’d tae ov Waqbar Vlelfxeidt. Lumeya .gori(0) qkum xfe tuwo izg qinec.
Vje vurbate vudfcefl “Uviqaaceob thelbux dqazi ex’b cugusf tai bask️”.
Iv yfu xiqs waci, xae’wk yiakf xete iteih tyi evmuc nfwec el qegriwmuekp aw Sopxal. You bii sfoni.
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.