Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Collections

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.

1. Basics:

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.

2. Lists:

Immutable List:

val numbers = listOf(1, 2, 3, 4, 5)

Mutable List:

val numbersMutable = mutableListOf(1, 2, 3)
numbersMutable.add(4)

3. Sets:

Immutable Set:

val fruits = setOf("apple", "banana", "cherry")

Mutable Set:

val fruitsMutable = mutableSetOf("apple", "banana")
fruitsMutable.add("cherry")

4. Maps:

Immutable Map:

val person = mapOf("name" to "Alice", "age" to 25)

Mutable Map:

val personMutable = mutableMapOf("name" to "Bob")
personMutable["age"] = 30

5. Collection Functions:

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.

6. Iterating through Collections:

Using for-loops:

for (number in numbers) {
    println(number)
}

For maps:

for ((key, value) in person) {
    println("$key = $value")
}

7. Collections and Nullability:

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()

8. Collections vs. Sequences:

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]

Conclusion:

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.

  1. List, Set, and Map in Kotlin:

    • List: Ordered collection with duplicate elements.
    • Set: Unordered collection with unique elements.
    • Map: Collection of key-value pairs.
    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)
    
  2. 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)
    
  3. 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")
    
  4. Filtering and mapping in Kotlin collections:

    • filter, map, flatMap.
    val evenNumbers = numbers.filter { it % 2 == 0 }
    val squareNumbers = numbers.map { it * it }
    
  5. Sorting collections in Kotlin:

    • sorted, sortedBy, sortedDescending, reversed.
    val sortedNumbers = numbers.sorted()
    val descendingNumbers = numbers.sortedDescending()
    
  6. 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()
    
  7. Iterating over collections in Kotlin:

    • for...in, forEach, forEachIndexed.
    for (fruit in fruits) {
        println(fruit)
    }
    
    fruits.forEach { println(it) }
    
  8. Transforming collections in Kotlin:

    • distinct, toSet, toMutableList.
    val uniqueNumbers = numbers.distinct()
    val setNumbers = numbers.toSet()
    val mutableList = numbers.toMutableList()
    
  9. Combining and merging collections in Kotlin:

    • plus, union, merge.
    val combinedList = numbers + moreNumbers
    val unionSet = set1 union set2
    
  10. Grouping and partitioning in Kotlin collections:

    • groupBy, partition.
    val groupByLength = fruits.groupBy { it.length }
    val (short, long) = fruits.partition { it.length <= 5 }
    
  11. 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 }
    
  12. Collections extension functions in Kotlin: Kotlin provides a rich set of extension functions for collections.

    val maxNumber = numbers.max()
    val chunkedNumbers = numbers.chunked(2)