Kotlin String - map() Function



The Kotlin string map() function is used to transform each character of a string into a new value based on a given transformation function and return a list containing the transformed values.

This function is useful for text transformation, converting characters to Unicode mapping, creating a list of transformed data, or data filtering with transformation.

The map() function does not modify the string; it creates a new list based on the transformation.

Syntax

Following is the syntax of the Kotlin string map() function −

fun CharSequence.map(transform: (Char) -> R): List

Parameters

This function accepts transform as a parameter which is a lambda function that defines how each character in the string should be transformed.

Return value

This function returns a list.

Example 1: Transform Character of String into UpperCase

This is the basic example of the map() function, we transform each character of this string into the upper case −

fun main(args: Array<String>) {
   val str = "Kotlin"
   // Transform each character to uppercase
   val result = str.map { it.uppercaseChar() }
   println("list: " + result)
}

Output

Following is the output −

list: [K, O, T, L, I, N]

Example 2: ASCII Value of Each Character

In this example, we use the map() function to get the ASCII values of each character of this string −

fun main(args: Array<String>) {
   val str = "abc"
   // Get ASCII values of each character
   val result = str.map { it.code }
   println(result)
}

Output

Following is the output −

[97, 98, 99]

Example 3: Perform Action on Each Character

Here, we add the prefix to each character of the string using the map() function −

fun main() {
   val str = "123"
   // Add a prefix to each character
   val result = str.map { "Number: $it" }
   println(result)
}

Output

Following is the output −

[Number: 1, Number: 2, Number: 3]
kotlin_strings.htm
Advertisements