Kotlin String associate()

Kotlin String associate() Tutorial

The associate() function of String class in Kotlin is used to associate each character of the string with a value calculated from that character.

The String associate() function creates a map where each character is a key, and the corresponding values are obtained by applying the provided transformation function to each character.

In this tutorial, we’ll explore the syntax of the associate() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the associate() function is as follows:

fun <K, V> CharSequence.associate(
    transform: (Char) -> Pair<K, V>
): Map<K, V>

where

ParameterDescription
transformA function that takes a character and returns a key-value pair.
Parameters of String.associate() function

The transform function is applied to each character in the string, and the resulting key-value pairs are used to create a map.

Examples for String associate() function

1. Creating a Map of Character Frequencies

In this example, we’ll use associate() to create a map of character frequencies in a given string.

  1. Take a string value in word.
  2. Define a transform function that returns a key-value pair with the character as the key and its frequency as the value.
  3. Call associate() function on word with the transform function. The function returns a map of character frequencies.
  4. You may print the resulting map to the console output.

Kotlin Program

fun main() {
    val word = "kotlin"

    // Using associate() to create a map of character frequencies
    val charFrequencyMap = word.associate { char -> char to word.count { it == char } }

    // Printing the resulting map
    println("Character Frequencies: $charFrequencyMap")
}

Output

Character Frequencies: {k=1, o=2, t=1, l=1, i=1, n=1}

2. Creating a Map of Character Codes

In this example, we’ll use associate() to create a map of characters and their corresponding ASCII codes in a given string.

  1. Take a string value in message.
  2. Define a transform function that returns a key-value pair with the character as the key and its ASCII code as the value.
  3. Call associate() function on message with the transform function. The function returns a map of character codes.
  4. You may print the resulting map to the console output.

Kotlin Program

fun main() {
    val message = "Hello, Kotlin!"

    // Using associate() to create a map of character codes
    val charCodeMap = message.associate { char -> char to char.toInt() }

    // Printing the resulting map
    println("Character Codes: $charCodeMap")
}

Output

Character Codes: {H=72, e=101, l=108, o=111, ,=44, K=75, t=116, i=105, n=110, !=33}

Summary

In this tutorial, we’ve covered the associate() function in Kotlin strings, its syntax, and how to use it to associate each character with a value calculated from that character. This function provides a versatile way to transform and organize string data into maps.