Open In App

Kotlin Collection Transformation

Last Updated : 15 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Kotlin Standard Library provides a rich set of extension functions for transforming collections. These transformations help us to build new collections or values derived from existing collections based on specific transformation logic. Kotlin supports several types of collection transformations, such as:

  1. Mapping
  2. Zipping
  3. Association
  4. Flattening
  5. String Representation

In this article, we will explore each of these transformations with simple explanations and examples.

1. Mapping

Mapping transforms the elements of a collection by applying a function to each element and returning a new collection containing the results. The core function for mapping is map().

  • map(): Applies a transformation to each element.
  • mapIndexed(): Includes the element's index as a parameter in the transformation.
  • mapNotNull(): Filters out null results after transformation.
  • mapIndexedNotNull(): Similar to mapNotNull(), but includes the element index.

Example:

Kotlin
fun main() {
    val numbers = listOf(1, 2, 3)
    val doubled = numbers.map { it * 2 }
    println("The new elements are: $doubled")

    val modified = numbers.mapIndexed { index, value -> if (index % 2 == 0) value * 2 else value * 1 }
    println("The modified elements are: $modified")
}

Output: 

The new elements are: [2, 4, 6]
The modified elements are: [2, 2, 6]

After transformation if we obtain null values on certain elements, we can easily filter out nulls from the collection only by calling the mapNotNull() function instead of map(), or mapIndexedNotNull() instead of mapIndexed().

Example: Removing Null Values with mapNotNull()

Kotlin
fun main() {
    val numbers = listOf(2, null, 4, null, 6)
    val result = numbers.mapNotNull { it }
    println("Numbers without null value: $result")
}

Output: 

Numbers without null value: [2, 4, 6]


2. Zipping

Zipping transformation help in building pairs by picking elements from both collections from the same indexing value and it can be done with the help of zip() extension function. It can be called on a collection or an array by passing another collection (array) as an argument and it returns the List of Pair objects. 
The first elements of pairs from the receiving collection and the second from the collection passed as an argument. If the collections sizes do not match then the resultant collection of the zip() is equivalent to the smaller size collection and the last elements of the larger collection are excluded from the results. It can also be called in the infix form a zip b.

Example: 

Kotlin
fun main() {
    val words = listOf("One", "Two", "Three", "Four")
    val numbers = listOf(1, 2, 3)
    val result = words.zip(numbers)
    println(result)
}

Output: 

[(One, 1), (Two, 2), (Three, 3)]

If we have a List of Pairs then we can do the reverse transformation with the help unzipping extension function which builds two lists from these pairs: 

  • The first list contains the first element of each pair from the original list.
  • The second list contains the second element from the original list.

Example: Unzipping collections

Kotlin
fun main() {
    val companies = listOf("Apple", "Google", "Amazon", "Facebook")
    val ranks = listOf(1, 2, 3, 4)
    val pairs = companies.zip(ranks)
    val (names, positions) = pairs.unzip()
    println("Unzipped: $names and $positions")
}

Output: 

Unzipped: [Apple, Google, Amazon, Facebook] and [1, 2, 3, 4]


3. Association

Association transformations help in building maps from the collection elements and certain values associated with them. Here, the basic association function is associateWith() which creates a Map in which original collection elements are the keys and associated values are obtained by the given transformation function from the original elements. 

Note: If we get two elements that are equal then only the last one remains on the map.

Example:

Kotlin
fun main() {
    val players = listOf("Kohli", "Root", "Smith", "Williamson")
    val scores = players.associateWith { it.length }
    println(scores)
}

Output: 

{Kohli=5, Root=4, Smith=5, Williamson=10}


4. Flattening

Flatten transformation helps in converting all the nested collections into single collection. If we operate nested collections, we find the standard library functions that provide flat access to nested collection elements useful.
The basic function is flatten() and we can call it on a collection of collections, for example, a List of Sets then it returns a single List of all the elements of the nested collections.

Example: 

Kotlin
fun main() {
    val openers = listOf(
        listOf("Warner", "Finch"),
        listOf("Roy", "Bairstow"),
        listOf("Rohit", "Dhawan"),
        listOf("Guptill", "Henry")
    )
    val allOpeners = openers.flatten()
    println("All openers: $allOpeners")
}

Output: 

All openers: [Warner, Finch, Roy, Bairstow, Rohit, Dhawan, Guptill, Henry] 


5. String representation

String representation means we can retrieve the collection content in a readable format. There are two functions that transform the collections to strings: 

  • joinToString()
  • joinTo()

The function joinToString() builds a single String from the collection elements based on the provided arguments. And function joinTo() also builds a single string but appends the result to the given Appendable object.
When the above functions called with the default arguments, both return the result similar to calling toString() on the collection: a String of elements' string representations separated by commas with spaces.

Example: 

Kotlin
fun main() {
    val colors = listOf("Red", "Green", "Blue", "Orange", "Yellow")

    println(colors) // Using toString()
    println(colors.joinToString()) // Default separator
    println(colors.joinToString(prefix = "Colors are: ", separator = ", "))
}

Output:  

[Red, Green, Blue, Orange, Yellow]
Red, Green, Blue, Orange, Yellow
Colors are: Red, Green, Blue, Orange, Yellow 

Article Tags :

Similar Reads