Kotlin Collections Cheat Sheet

Here’s a Kotlin collections cheat sheet:

List

Create a List:

val list = listOf("apple", "banana", "orange")

Mutable List:

val mutableList = mutableListOf("apple", "banana", "orange")

Access Element:

val firstElement = list[0]

Add Element:

mutableList.add("grape")

Remove Element:

mutableList.remove("banana")

Set

Create a Set:

val set = setOf("apple", "banana", "orange")

Mutable Set:

val mutableSet = mutableSetOf("apple", "banana", "orange")

Add Element:

mutableSet.add("grape")

Remove Element:

mutableSet.remove("banana")

Map

Create a Map:

val map = mapOf("fruit" to "apple", "color" to "red")

Mutable Map:

val mutableMap = mutableMapOf("fruit" to "apple", "color" to "red")

Access Value:

val fruit = map["fruit"]

Add/Update Entry:

mutableMap["size"] = "medium"

Remove Entry:

mutableMap.remove("color")

Collection Operations

Filter Elements:

val filteredList = list.filter { it.startsWith("a") }

Map Elements:

val lengths = list.map { it.length }

Sort Elements:

val sortedList = list.sorted()

Group Elements:

val groupedByLength = list.groupBy { it.length }

Functional Operations

forEach:

list.forEach { println(it) }

fold:

val sum = list.fold(0) { acc, item -> acc + item.length }

any / all:

val anyStartsWithA = list.any { it.startsWith("a") }
val allStartsWithA = list.all { it.startsWith("a") }

This Kotlin collections cheat sheet covers some basic operations for lists, sets, and maps. Kotlin’s collections library provides a rich set of functions, so always refer to the official Kotlin documentation for more details and advanced features.