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 – 
 

Kotlin




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

 



Kotlin | Collection Transformation

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

 

Similar Reads

Mapping –

The mapping transformation is used to create a collection from the obtained results of a function on the elements of 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 is 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 –...

Zipping –

...

Association –

...

Flattening –

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.Kotlin program of using zip() method –...

String representation –

...