Kotlin Set - map() Function



The Kotlin Set map() function works seamlessly as a set collection just like it does with a list. It is used to convert a set of items into another. It applies the specified lambda function to each element of the original collection and returns them to a newly created list.

As compared to the list set does not allow duplicate element so the result of the transformation also does not allow the duplicate.

There are the following use cases of the map() function:

  • Transform the set
  • Extract properties form object
  • Mapping to different data types
  • Combining data from multiple collection

Syntax

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

val result = originalSet.map { transformFunction(it) }

Parameters

This function accepts lambda function to define a transformation logic.

Return value

This function returns a list containing the results of applying the given transform function.

Example 1: Square of the Set Elements

Let's see a basic example of the map() function, which return a list containing square of each element −

fun main(args: Array<String>) {
   val numbers = setOf(2, 3, 4)
   println(numbers.map { it * it })
}

Output

Following is the output −

[1, 4, 9]

Example 2: Chaining with Other Function

In the following example, we filter the even element in the set and use the map function to calculate the square of the even element −

fun main(args: Array<String>) {
   val numbers = setOf(2, 3, 4, 5)
   val square = numbers.filter { it % 2 == 0 }.map { it * it }
   println(square)
}

Output

Following is the output −

[4, 16]

Example 3: Convert Words to their lengths

This is another example of the map() function to transform the words of a set by their length and filter out words with length less than 6 −

fun main(args: Array<String>) {
   val words = setOf("Kotlin", "Java", "Swift", "Python", "JavaScript")

   val longWordsLengths = words.map { it.length }.filter { it >= 6 }

   println(longWordsLengths)
}

Output

Following is the output −

[6, 6, 10]
kotlin_sets.htm
Advertisements