Sobes.tech
Junior

How to work with collections in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, collections are groups of objects. They can be mutable or immutable.

Immutable Collections:

  • Contents cannot be changed after creation.
  • Thread-safe for reading.
  • Basic types: List, Set, Map.
val numbers: List<Int> = listOf(1, 2, 3) // Creating an immutable list
// numbers.add(4) // Compilation error: immutable collection

Mutable Collections:

  • Contents can be changed (adding, removing, modifying elements).
  • Not thread-safe by default (manual synchronization required).
  • Basic types: MutableList, MutableSet, MutableMap.
val mutableNumbers: MutableList<Int> = mutableListOf(1, 2, 3) // Creating a mutable list
mutableNumbers.add(4) // Adding an element
mutableNumbers.remove(2) // Removing an element

Main Collection Types:

  • List: Ordered collection allowing duplicates. Access by index.
    val names: List<String> = listOf("Alice", "Bob", "Alice")
    println(names[0]) // "Alice"
    
  • Set: Unordered collection, no duplicates allowed. Elements are stored uniquely.
    val uniqueNumbers: Set<Int> = setOf(1, 2, 2, 3)
    println(uniqueNumbers) // [1, 2, 3]
    
  • Map: Collection of key-value pairs. Each key is unique.
    val ages: Map<String, Int> = mapOf("Alice" to 30, "Bob" to 25)
    println(ages["Alice"]) // 30
    

Extension functions for working with collections (higher-order functions):

Kotlin provides many powerful extension functions for collection processing:

  • filter: Creates a new collection containing only elements satisfying a predicate.
    val evenNumbers = numbers.filter { it % 2 == 0 } // [2]
    
  • map: Transforms each element into a new element, creating a new collection.
    val squaredNumbers = numbers.map { it * it } // [1, 4, 9]
    
  • forEach: Performs an action for each element.
    numbers.forEach { println(it) } // Prints 1, 2, 3 line by line
    
  • reduce: Combines all elements into a single value using an operation.
    val sum = numbers.reduce { acc, i -> acc + i } // 6
    
  • fold: Similar to reduce, but takes an initial value.
    val sumWithInitial = numbers.fold(10) { acc, i -> acc + i } // 16 (10 + 1 + 2 + 3)
    
  • sortedBy: Sorts the collection by a value obtained from each element.
    val sortedNames = listOf("Charlie", "Alice", "Bob").sortedBy { it } // [Alice, Bob, Charlie]
    
  • groupBy: Groups elements by a key obtained from each element.
    val groupedNumbers = numbers.groupBy { if (it % 2 == 0) "even" else "odd" } // {odd=[1, 3], even=[2]}
    

Conversion between collection types:

You can easily convert one collection type to another, as well as between mutable and immutable versions:

val mutableList: MutableList<Int> = listOf(1, 2, 3).toMutableList()
val immutableList: List<Int> = mutableListOf(4, 5, 6).toList()

Working with collections in Kotlin is greatly simplified thanks to the rich standard library and extension functions.

How to work with collections in Kotlin? — Kotlin - sobes.tech