Collection Kotlin

Array

fun main(args: Array<String>) { // Elements : 32 0 0 54 0 // Index : 0 1 2 3 4 var myArray = Array<Int>(5) { 0 } // Mutable. Fixed Size. myArray[0] = 32 myArray[3] = 54 myArray[1] = 11 for (element in myArray) { // Using individual elements (Objects) println(element) } println() for (Index in 0..myArray.size - 1) { println(myArray[index]) } }

Collection

List

fun main(args: Array<String>) { // Elements : // Index : 0 1 2 3 4 // var list = mutableListOf<String>() // Mutable, No Fixed Size, Can Add or Remove Elements // var list = arrayListOf<String>() // Mutable, No Fixed Size, Can Add or Remove Elements var list = ArrayList<String>() // Mutable, No Fixed Size, Can Add or Remove Elements list.add("Yogi") // 0 list.add("Manmohan") // 1 list.add("Vajpayee") // 2 // list.remove("Manmohan") // list.add("Vajpayee") list[1] = "Modi" for (element in list) { // Using individual elements (Objects) println(element) } }

listOf

Inmutable, Fixed Size, Read ONLY

mutableListOf, arrayListOf, ArrayList

Mutable, READ and WRITE both, No Fixed Size

Map

// Map Tutorial: Key-Value pair // var myMap = HashMap<Int, String>() // Mutable, READ and WRITE both, No Fixed Size // var myMap = mutableMapOf<Int, String>() // Mutable, READ and WRITE both, No Fixed Size var myMap = hashMapOf<Int, String>() // Mutable, READ and WRITE both, No Fixed Size myMap.put(4, "Yogi") myMap.put(43, "Manmohan") myMap.put(7, "Vajpayee") myMap.put(43, "Modi") for (key in myMap.keys) { println("Element at $key = ${myMap[key]}") // myMap.get(key) }

mapOf

Inmutable, Fixed Size, Read ONLY

HashMap, mutableMapOf, hashMapOf

Mutable, READ and WRITE both, No Fixed Size

Set

fun main(args: Array<String>) { // "Set" contains unique elements // "HashSet" also contains unique elements but sequence is not guaranteed in output var mySet = mutableSetOf<Int>( 2, 54, 3, 1, 0, 9, 9, 9, 8) // Mutable Set, READ and WRITE both // var mySet = hashSetOf<Int>( 2, 54, 3, 1, 0, 9, 9, 9, 8) // Mutable Set, READ and WRITE both mySet.remove(54) mySet.add(100) for (element in mySet) { println(element) } }

setOf -> contains unique elements

Inmutable, Fixed Size, Read ONLY

Set -> contains unique elements

HashSet -> also contains unique elements but sequence is not guaranteed in output

Mutable, READ and WRITE both, No Fixed Size