Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Collections in Kotlin are powerful tools that let you store and manipulate groups of items. Kotlin provides a rich set of collection interfaces, immutable and mutable implementations, and a multitude of extension functions to work with them efficiently.
Kotlin has two main types of collections:
Immutable (read-only): By default, Kotlin collections are immutable. They can't be modified after creation.
Mutable: Kotlin also provides mutable versions of collections which can be changed after creation.
Immutable List:
val numbers = listOf(1, 2, 3, 4, 5)
Mutable List:
val numbersMutable = mutableListOf(1, 2, 3) numbersMutable.add(4)
Immutable Set:
val fruits = setOf("apple", "banana", "cherry")
Mutable Set:
val fruitsMutable = mutableSetOf("apple", "banana") fruitsMutable.add("cherry")
Immutable Map:
val person = mapOf("name" to "Alice", "age" to 25)
Mutable Map:
val personMutable = mutableMapOf("name" to "Bob") personMutable["age"] = 30
Kotlin provides a wide variety of extension functions for collections.
Filtering:
val evenNumbers = numbers.filter { it % 2 == 0 }
Mapping:
val doubled = numbers.map { it * 2 }
Finding elements:
val firstEven = numbers.find { it % 2 == 0 }
Folding:
val sum = numbers.fold(0) { acc, i -> acc + i }
And many more: sorted
, groupBy
, flatten
, plus
, minus
, distinct
, etc.
Using for-loops:
for (number in numbers) { println(number) }
For maps:
for ((key, value) in person) { println("$key = $value") }
Kotlin's type system inherently supports nullability. Collections can have nullable types, and you often encounter functions like filterNotNull
to deal with them:
val nullableList = listOf(1, 2, null, 4) val nonNulls = nullableList.filterNotNull()
Kotlin also provides sequences (Sequence<T>
), which represent a lazily evaluated collection. They can be especially useful when working with large data sets or performing chain operations, as they don't create intermediate collections.
val sequence = numbers.asSequence() .map { it * 2 } .filter { it % 3 == 0 } .toList() // [6, 12]
Kotlin's collection framework, combined with its extension functions, offers a powerful and expressive system for managing and manipulating groups of items. Familiarity with these concepts can significantly increase productivity and reduce the chances of errors in your Kotlin applications.
List, Set, and Map in Kotlin:
val myList = listOf(1, 2, 3, 4, 5) val mySet = setOf("apple", "banana", "orange") val myMap = mapOf("one" to 1, "two" to 2, "three" to 3)
Creating collections in Kotlin:
Collections can be created using various functions like listOf
, mutableListOf
, setOf
, mutableSetOf
, mapOf
, mutableMapOf
.
val numbers = listOf(1, 2, 3, 4, 5) val mutableNumbers = mutableListOf(1, 2, 3, 4, 5)
Common operations on Kotlin collections:
size
, isEmpty
, contains
, add
, remove
, clear
.val fruits = mutableListOf("apple", "banana", "orange") println(fruits.size) fruits.add("grape") fruits.remove("banana")
Filtering and mapping in Kotlin collections:
filter
, map
, flatMap
.val evenNumbers = numbers.filter { it % 2 == 0 } val squareNumbers = numbers.map { it * it }
Sorting collections in Kotlin:
sorted
, sortedBy
, sortedDescending
, reversed
.val sortedNumbers = numbers.sorted() val descendingNumbers = numbers.sortedDescending()
Working with nullable elements in Kotlin collections: Collections can hold nullable elements. Use safe calls or filters to handle nullable elements.
val nullableList: List<Int?> = listOf(1, 2, null, 4) val nonNullList = nullableList.filterNotNull()
Iterating over collections in Kotlin:
for...in
, forEach
, forEachIndexed
.for (fruit in fruits) { println(fruit) } fruits.forEach { println(it) }
Transforming collections in Kotlin:
distinct
, toSet
, toMutableList
.val uniqueNumbers = numbers.distinct() val setNumbers = numbers.toSet() val mutableList = numbers.toMutableList()
Combining and merging collections in Kotlin:
plus
, union
, merge
.val combinedList = numbers + moreNumbers val unionSet = set1 union set2
Grouping and partitioning in Kotlin collections:
groupBy
, partition
.val groupByLength = fruits.groupBy { it.length } val (short, long) = fruits.partition { it.length <= 5 }
Using sequences in Kotlin collections: Sequences are like lazy collections that allow for more efficient operations on large datasets.
val sequence = numbers.asSequence().map { it * 2 }.filter { it % 3 == 0 }
Collections extension functions in Kotlin: Kotlin provides a rich set of extension functions for collections.
val maxNumber = numbers.max() val chunkedNumbers = numbers.chunked(2)