Skip to content
Related Articles

Related Articles

Improve Article

Kotlin | Collection Transformation

  • Last Updated : 05 Sep, 2019

Kotlin standard library provides different set of extension functions for collection transformations. These functions help in building new collections from existing collections based on the rules defined by the transformation.

There are different number of transformation functions:

  • Mapping
  • Zipping
  • Association
  • Flattening
  • String representation

Mapping –

The mapping transformation is used to create a collection from the obtained results of a function on the elements of some another collection and the base function used for mapping is map(). When apply the given lambda function to each subsequent element it returns the list of the lambda results.
It maintains the order of the element as stored in the original collection. In order to apply a transformation that additionally uses the element index as an argument we can use the mapIndexed().

Kotlin program of mapping –




fun main(args : Array<String>) {
    val numbers = setOf(1, 2, 3)
  
    // multiple all elements by 2
    println("The new elements are: "+numbers.map { it * 2 })
  
    // multiple idx with element
    println("The modified elements are: "+numbers.mapIndexed 
    { idx, value -> value * idx })
}

Output:



The new elements are: [2, 4, 6]
The modified elements are: [0, 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().




fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3)
  
    // filter out the null values and print
    println("Numbers without null value: "+numbers.mapNotNull
    { if ( it == 1) null else it * 2 })
  
    println("Numbers without null value: "+numbers.mapIndexedNotNull
    { idx, value -> if (idx == 0) null else value * idx })
}

Output:

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

Zipping –

Zipping transformation help in building pairs by picking elements from both collections from the same indexing value and it can be done 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 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 excluded from the results. It can also be called in the infix form a zip b.

Kotlin program of using zip() method –




fun main(args: Array<String>) {
    val numbers = listOf("One","Two","Three","four")
    val integers = listOf(1,2,3,4)
  
    // pair string number with integers
    println(numbers zip integers)
  
    val newInt = listOf(1,2)
    // pair string with less than numbers
    println("New pairs :"+numbers.zip(newInt))
}

Output:

[(One, 1), (Two, 2), (Three, 3), (four, 4)]
New pairs :[(One, 1), (Two, 2)]

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:

  • First list contains the first element of each Pair from the original list.
  • The second list contains the second elements from the original list.

Kotlin program of using the unzip() method –






fun main(args: Array<String>) {
    val companies = listOf("Apple" to 1, "Google" to 2,
        "Amazon" to 3, "Facebook" to 4)
  
    // print after unzip the pairs
    println("Pairs unzipped: "+companies.unzip())
}

Output:

Pairs unzipped: ([Apple, Google, Amazon, Facebook], [1, 2, 3, 4])

Association –

Association transformations help in building maps from the collection elements and certain values associated with them. Here, 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 are equal then only the last one remains in the map.

Kotlin program of using associateWith() method –




fun main(args: Array<String>) {
  
    val captains = listOf("Kohli", "Root", "Smith", "Williamson","Root")
      
    // print the elements associated with their length
    println(captains.associateWith { it.length })
}

Output:

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

Flattening –

Flatten transformation helps in converting all the nested collection 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.

Kotlin program of using flatten() method –




fun main(args: Array<String>) {
  
    val openers = listOf(setOf("Warner", "Finch") ,setOf("Roy","Bairstow")
        ,setOf("Rohit,Dhawan"),setOf("Guptill","Henry"))
  
    // print the elements associated with their length
    println("All the openers are: "+openers.flatten())
}

Output:

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

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.

Kotlin program of using string representation methods –




fun main(args: Array<String>) {
    val colors = listOf("Red","Green","Blue","Orange","Yellow")
  
    println(colors)
    // join all elements in a single List
    println(colors.joinToString())
  
    val listString = StringBuffer("Colors are: ")
    colors.joinTo(listString)
    println(listString)
}

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :