Pandiyan Mani
2 min readSep 14, 2021

--

Collections in Kotlin

Collections is a framework that provides you an architecture to store and manipulate a group of object.

By using collection we can perform insertion,deletion,manipulation,searching and sorting.

Collection provide us an interface like list,map and set.

Collection are classified in to two types:

immutable → it provide only with read only option we cannt add or remove element on this type.

mutable → we can modify the object we can perform read,write and delete data from the coollection.

lets see the collections under two types first we see with immutable types

listOf ()→it comes under immutable type, list is an interface which provide method of read only operation we cannt add or delete data from it.

val immutablelis:List<String> = listOf("A", "B")
println(immutablelis)

mapOf() → it comes under immutable type,map is an interface which provide method of read only operation we cannt add or delete data from it.It stores data in the form of key and value.In hashmap always the key should be unique we can have duplicate values but not same key.

val immutablemapobj:Map<Int, String> = mapOf(1 to "a", 2 to "b")
println(immutablemapobj)

setOf ()→it comes under immutable type,set is an interface which provide method of read only operation we cannt add or delete data from it.It does not allow duplicate value of same type.

val mutuablesetobj:MutableSet<Int> = mutableSetOf(1,2,3)
mutuablesetobj.add(3)
output:[1, 2]

in the above exmple the value 3 wont be inserted since the set already contain value of 3 in its collection

lets see the collections under mutable types

mutuableListOf ()→we can add and remove element from the collection

val mutablelis:MutableList<String> = mutableListOf("A", "B")
mutablelis.add("C")
println(mutablelis)
Output:[A, B, C]

mutableMapOf() →we can add element using key and value here instead of add we use put to insert element.It maintain the insertion order because it follow the concept of LinkedHashMap.

val mutuablemapobj:MutableMap<Int, String> = mutableMapOf(1 to "a", 2 to "b")
mutuablemapobj.put(3, "c")
println(mutuablemapobj)
Output:{1=a, 2=b, 3=c}

hashMapOf() →the difference between mutableMapOf and hashMapOf is hashMapOf doesnt maintain the insertion order because it follow the concept of HashMap wheres mutableMapOf maintain the insertion order.

val mutuablehashmapobj:MutableMap<Int, String> = hashMapOf(2 to "b",1 to "a" )
println(mutuablehashmapobj)
Output:{1=a, 2=b}

mutableSetOf() →it doesnt allow duplicate value we can add and remove element.

val mutuablesetobj:MutableSet<Int> = mutableSetOf(1,2,3)
mutuablesetobj.add(3)
println(mutuablesetobj)
Output:[1, 2]

--

--