Collection processing in Kotlin: Ending
This is a chapter from the book Functional Kotlin. You can find it on LeanPub or Amazon. It is also available as a course.
When we need to transform an iterable into a string, and toString
is not enough, we use the joinToString
function. In its simplest form, it just presents elements (using their toString
method) one after another, separated with commas. However, joinToString
is highly customisable with optional arguments:
separator
(", "
by default) - decides what should be between the values in the produced string.prefix
(""
by default) andpostfix
(""
by default) - decide what should be at the beginning and at the end of the string.prefix
andpostfix
are also displayed for an empty collection.limit
(-1
by default, which means no limit) andtruncated
("..."
by default) -limit
decides how many elements can be displayed. Once the limit is reached,truncated
is shown instead of the rest of the elements.transform
(toString
by default) - decides how each element should be transformed toString
.
Map
, Set
and String
processing
Most of the presented functions are extensions on either Collection
or on Iterable
, therefore they can be used not only on lists but also on sets. However, in addition to List
and Set
, there is also the third most important data structure: Map
. It does not implement Collection
or Iterable
, so it needs custom collection processing functions. It has them! Most of the functions we have covered so far are also defined for the Map
interface.
The biggest difference between collection and map processing methods stems from the fact that elements in maps are represented by both a key and a value. So, in functional arguments (predicates, transformations, selectors), instead of operating on values we operate on entries (the Map.Entry
interface represents both a key and a value). When values are transformed (like in map
or flatMap
), the result type is List
, unless we explicitly transform just keys or values (like in mapValues
or mapKeys
).
String
is another important type. It is considered a collection of characters, but it does not implement Iterable
or Collection
. However, to support string processing, most collection processing functions are also implemented for String
. However, String
also supports many other operations, but these are better explained in the third part of the Kotlin for developers series: Advanced Kotlin.