Learning Kotlin Programming

Kotlin Collection Functions Cheat Sheet

Enable learning and finding relevant collection function easier

Elye
Elye
May 25, 2020 · 12 min read

Kotlin provides a rich utility set of functions for its collections. There are about 200 of them. To use them, one needs to know that they exist. It is hard to scan through 200 of them alphabetically to find which is relevant. Hence I’m making a cheat sheet for the functions, grouping them based on its functionality. Hopefully making learning and finding what you want easier.

I’m grouping them into 5 categories as below.

  1. Creation — Functions that create a collection, e.g. listOf

In the document, for some of the functions that are not easily understood, I’ll provide some illustration, while the others that are named clearer, I provide a link to their respective formal documentation.

Check through them once to get your familiarity with the sections, and in the future, you could easily find what you want.

For example 1 :

If you like to look for a function that does the multiplication of all the integer items value in the list.

Since the final result is a single generated value from all the items, one can go to search for the relevant function in the Conclude category.

Go through the functions, you’ll find you can do it with reduce

list.reduce{ result, item -> result * item }

For example 2 :

If you like to look for a function break your list into multiple sublists of smaller fixed size.

The final result is transforming the existing list into another form of collection. The category that most fitted such function would be the Change category.

Go through the functions, you’ll find you can do it with chunk

list.chunked(3)

Relationship between the categories

From the categories, it is obvious Creation is the first state as it creates the collections, Change and Convert is the intermediary state where they can transition between themselves, while the final state is either Conclude or Choose.

For example

listOf(1, 2, 3)   // Creation
.map { it * 2 } // Change
.sum() // Conclude

Of course, the first stage could go to the final state skipping the intermediary state e.g.

listOf(1, 2, 3)   // Creation
.sum() // Conclude

Notes, some of the functions do have variation helper function with appended By, To and With. Check out this to make them easily understood.

Also for function that is original word and it’s past-participle, the below blog helps explains

Creation Category

In this category, I further break them down into subcategories, to make finding them easier.

  1. Creation Compose — Instantiate new collection

1. Creation Compose — instantiate new collection

These are the functions that help you instantiate the collections directly. They are all linked to the formal Kotlin documentation.

// Empty Collection
emptyList, emptyMap, emptySet
// Read-only Collection
listOf, mapOf, setOf
// Mutable Collection
mutableListOf, mutableMapOf, mutableSetOf, arrayListOf
// Build Collection from mix sources
buildList, buildMap, buildSet
// Linked Collection
linkedMapOf, linkedSetOf (more in stackOverflow)
// Sorted Collection
sortedMapOf, sortedSetOf (more in stackOverflow)
// Hash Collection
hashMapOf, hashSetOf (more in stackOverflow)
// Programmatically create Collection
List, MutableList, Iterable

2. Creation Copy — replicate of collection

This is mainly for replicating array

copyInto     // Can into array
copyOfRange // Partially copy
copyOf // Copy fully
toCollection // Copy into collection

3. Creation Catch — like try-catch to create otherwise

ifEmpty         // if empty give a default
orEmpty // change null into empty
requireNoNulls // crash if any element is null
listOfNotNull // make single element list or null

Conversion Category

This is the category, where the function will try to change the type of the collection to another type. I further break them down into subcategories, to make finding them easier.

  1. Conversion Copy — convert to another type of a new collection

One good example is toIntArray (Copy) and asIntArray (Cite):

// toIntArray example (a new copy)
val uIntArray = UIntArray(3) { 1U }
val toIntArray = uIntArray.toIntArray()
toIntArray[1] = 2
println(toIntArray.toList()) // [1, 2, 1]
println(uIntArray.toList()) // [1, 1, 1]
// asIntArray example (a reference copy)
val uIntArray = UIntArray(3) { 1U }
val asIntArray = uIntArray.asIntArray()
asIntArray[1] = 2
println(asIntArray.toList()) // [1, 2, 1]
println(uIntArray.toList()) // [1, 2, 1]

1. Conversion Copy — convert to another type of a new collection

// to array type
toBooleanArray, toByteArray, toCharArray, toDoubleArray, toFloatArray, toIntArray, toLongArray, toShortArray, toTypedArray, toUByteArray, toUIntArray, toULongArray, toUShortArray
// to read-only collection
toList, toMap, toSet
// to mutable collection
toMutableList, toMutableMap, toMutableSet, toHashSet
// to sorted collection
toSortedMap, toSortedSet
// Convert Entries to Pair
toPair // More illustration below
// Convert Map to Properties
toProperties // More illustration below

toPair to convert map entry to Pair instead. Example code below.

map.entries.map { it.toPair() }// This is essentially 
map.toList()
// Underlying `toList` of Map, it is using `toPair()`
// to do all the conversion of entries to Pair

toProperties to convert Map to Properties (a Java native class). It is a subclass of Map<String, String> though.

val map = mapOf("x" to "value A", "y" to "value B")
val props = map.toProperties()
println(props.getProperty("x")) // value A
println(props.getProperty("z")) // null
println(props.getProperty("y", "fail")) // value B
println(props.getProperty("z", "fail")) // fail
println(map.get("x")) // value A
println(map.get("z")) // null
println(map.getOrDefault("y", "fail")) // value B
println(map.getOrDefault("z", "fail")) // fail

2. Conversion Cite — convert to another type with a reference to the origin

// as array type
asByteArray, asIntArray, asLongArray, asShortArray, asUByteArray, asUIntArray, asULongArray, asUShortArray,
// as collection type. For list vs sequestion, check this blog
asIterable, asList, asSequence
// Convert to indexed iterator
withIndex // More illustration below
// Convert to Map with customized default
withDefault // More illustration below

withIndex to convert List to IndexedValue iterable (iterator with index).

val list = listOf("A", "B", "C")
val indexed = list.withIndex()
println(list) // [A, B, C]println(indexed.toList())
// [IndexedValue(index=0, value=A),
// IndexedValue(index=1, value=B),
// IndexedValue(index=2, value=C)]

withDefault to convert Map to a Map with customized DefaultValue

val map = mutableMapOf(1 to 1)// customize default value return x 2 of key
val default = map.withDefault { k -> k * 2 }
println(default.getValue(10)) // return 20
println(map.getValue(10)) // crash as no key 10

Change Category

This is the category, where the function will change the content of the collection or result in a different structure of the collection. I further break them down into subcategories, to make finding them easier.

  1. Change Content — the result of the functions here would retain the original collection type (e.g. List function that output List), and the element type is also retained (e.g. if the element type is Int, this result element type is also Int). e.g. filter function.

1. Change Content — change the content but not the structure

In Change Content, we have two types, i.e.

  • Generate a new collection and change the content of it, and return it

A simple example is add vs plus

val list = listOf(1)
val mutableList = mutableListOf(1)
println(list) // [1]
println(mutableList) // [1]
val newList = list.plus(2)
mutableList.add(2)
println(list) // [1]
println(newList) // [1, 2]
println(mutableList) // [1, 2]

They both are of the same purpose but resulted differently as above. To differentiate them, I’ll make the mutated function as italic. i.e. add, while the create a new list result as non-italic i.e. plus

plus, add

Let’s check out the function list.

// Changing content
set, setValue //(more info in stackoverflow)
// Adding content
plus, plusElement, //(more info in stackoverflow)
plusAssign, //(more info in stackoverflow)
add, addAll, put, putAll
// Removing content
minus, minusElement, //(more info in stackoverflow)
minusAssign, //(more info in stackoverflow)
remove
// Remove away from the front or behind of the collection
drop
, dropLast, dropLastWhile, dropWhile,
removeFirst, removeFirstOrNull, removeLast, removeLastOrNull,
// Pick from the front or behind part of the collection
take, takeLastWhile, takeLast, takeWhile,
// Pick from the center section of the collection
slice, sliceArray
// Get distinct (unique) value only
distinct, distinctBy
// Perform venn diagram operation given two collections
union, intersect retainAll, subtract removeAll
// Transform the content to another value
map, mapTo, mapIndexed, mapIndexedTo, mapKeys, mapKeysTo, mapValues, mapValuesTo, replaceAll, fill
// Transform the content and remove all null
// to have non-nullable result of content
mapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo

Note: map function can also change the list to another form or different type (i.e. Change Contour subcategory)

// Filter some content away
filter, filterIndexed, filterIndexedTo, filterIsInstance, filterIsInstanceTo, filterKeys, filterNot, filterNotNull, filterNotNullTo, filterNotTo, filterTo, filterValues
// Reverse the content value 
// (Checkout the article for their differences)
reversed, reversedArray, reverse, asReversed
// Sort the content value
sorted, sortedArray, sortedArrayDescending, sortedArrayWith, sortedBy, sortedByDescending, sortedDescending, sortedWith sort, sortBy, sortByDescending, sortDescending, sortWith
// Randomize the content sequence
shuffle, shuffled
// Like fold or reduce, but done on each elements incrementally
scan, scanIndexed, scanReduce, scanReduceIndexed

2. Change Contour — change the content and the structure

In this category, the result of the function will change the structure e.g. List to Map or the structure or the content, e.g. List<String> to List<Map>.

Let’s look into the function list

// Form a map of aggregated items
aggregate
, aggregateTo //(require groupingBy)
// Example
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val aggregated = numbers.groupingBy { it % 3 }
.aggregate { key, accumulator: Int?, element, first ->
if (first) element else accumulator?.plus(element)
}
println(aggregated) // {1=12, 2=15, 0=18}
// Form a map of number of related items
eachCount, eachCountTo //(require groupingBy)
// Example Code
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val eachCount = numbers.groupingBy { it % 2 }.eachCount()
println(eachCount) // {1=5, 0=4}
// Link each item with a map key
associate, associateBy, associateByTo, associateTo, associateWith, associateWithTo //(check this article for their differences)
// Example code
val list = listOf(1, 2, 3, 4, 5)
val associate = list.associateWith { it * it }
println(associate) // {1=1, 2=4, 3=9, 4=16, 5=25}
// Group related items together into map of List
groupBy, groupByTo
// Example code
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val groupBy = list.groupBy{it % 3}
println(groupBy)
// Flatten into single list.
flatMap
, flatMapTo, flatten
// Example code
val map = mapOf(1 to listOf(1, 2), 2 to listOf(2, 4))
val flatMap = map.flatMap { it.value }
println(flatMap) // [1, 2, 2, 4]
// Example code
val list = listOf(listOf(1, 2), listOf(2, 4))
val flatten = list.flatten()
println(flatten) // [1, 2, 2, 4]
// Transform the content to another type value
map, mapTo, mapIndexed, mapIndexedTo, mapKeys, mapKeysTo, mapValues, mapValuesTo
// Transform the content and remove all null
// to have non-nullable result of content
mapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo
// Example code
val days = listOf("Monday", "Tuesday", "Wednesday", "Thursday")
val daysLength = days.map { it.length }
println(daysLength)
// Categorize items into different list
chunked, partition, windowed
// Example code
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val chunked = list.chunked(4)
val windowed = list.windowed(4, 3, true)
val partition = list.partition { it % 2 == 0 }
println(chunked) // [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
println(windowed) // [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9]]
println(partition)// ([2, 4, 6, 8], [1, 3, 5, 7, 9])
// Join two item together (or unjoin)
zip, zipWithNext, unzip
// Example code
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(6, 7, 8, 9)
val zip = list.zip(list2)
println(zip)
// Example code
val list = listOf(1, 2, 3, 4)
val zipWithNext = list.zipWithNext()
println(zipWithNext)
// Example code
val list = listOf(1 to 2, 3 to 4, 5 to 6)
val unzip = list.unzip()
println(unzip)

Choose Category

This is the category, where the function will access a specific element in the collection. I further break them down into subcategories, to make finding them easier.

  1. Choose Certain — The functions is certain where to get the element

Regardless, the result is one of the elements within the collection.

1. Choose Certain — is certain where to get the element

Some of these functions look so similar. Check out below for their differences

// For List and Map mostly
get
, getOrDefault, getOrElse, getOrNull, getOrPut,
getValue // (more info in stackoverflow and check withDefault above)
// Mainly for sequence and set
elementAt, elementAtOrElse, elementAtOrNull
// For destructuring usage
component1, component2, component3, component4, component5
// Randomly get any element
random, randomOrNull
// If intent to manually iterate though
iterator
// Make sure to get the one any only element
single, singleOrNull

2. Choose Clue — will search for the element when given a clue

We provide the function of what we like to look for, and the function will find the element matching it.

// Search from beginning first element
find, first, firstOrNull
// Search from behind first element
findLast, last, lastOrNull
// Search for the index
indexOf, lastIndexOf, indexOfFirst, indexOfLast
// Search on a sorted collection
binarySearch, binarySearchBy

Conclude Category

This is the category, where the functions are to evaluate though all relevant elements to produce some result. I further break them down into subcategories, to make finding them easier.

  1. Conclude Choice — The functions will result in a Boolean e.g. isEmpty

1. Conclude Choice

// Check for existance
all, any, none
contains, containsAll, containsKey, containsValue
isEmpty, isNotEmpty, isNullOrEmpty (check article)
// Comparison
contentEquals, contentDeepEquals

2. Conclude Compute

// Statistical related
average, count, max, maxBy, maxWith, min, minBy, minWith
sum, sumBy, sumByDouble (double float type)
// Deductive computation (similar to scan)
fold, foldIndexed, foldRight, foldRightIndexed, foldTo,
reduce, reduceIndexed, reduceOrNull, reduceRight,
reduceRightIndexed, reduceRightOrNull, reduceTo

3. Conclude Combine

// Generate hash code
contentHashCode, contentDeepHashCode
// Generate string
contentToString, contentDeepToString,
joinTo, joinToString, subarrayContentToString

3. Conclude Carryover

// Final loop through
forEach, forEachIndexed
// It the middle loop through
// return the collection itself
// (like side effect function)
onEach
The different of forEach() and onEach() function

Single Cheat Sheet

After all the explanation above, provided below a single sheet of all the functions, that could be print out and stick on the wall 🙂

Kotlin Collection Functions Cheat Sheet

Thanks for reading. You can check out my other topics here, join my at Twitter, or Facebook.

Mobile App Development Publication

Sharing Mobile App Development and Learning

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store