map

Kotlin collections methods: examples and syntax

As a quick note today, if you ever need some examples of how the Kotlin collections methods work, I hope these examples are helpful.

Sample data

First, here’s some sample data:

val a = listOf(10, 20, 30, 40, 10)
val names = listOf("joel", "ed", "chris", "maurice")

Kotlin groupBy syntax and example

Here’s a quick example of how to use the Kotlin groupBy syntax on a list, with the result of each example shown in the comments:

val names = listOf("kim", "julia", "jim", "hala")

names.groupBy { it -> it.length }  //LinkedHashMap: {3=[kim, jim], 5=[julia], 4=[hala]}
names.groupBy({it}, {it.length})   //LinkedHashMap: {kim=[3], julia=[5], jim=[3], hala=[4]}

Kotlin functions to create Lists, Maps, and Sets

Table of Contents1 - Kotlin Arrays2 - Kotlin List functions3 - Kotlin Map functions4 - Kotlin Set functions5 - Summary: Kotlin List, Map, and Set creation functions

With Kotlin you can create lists, maps, and sets with standard functions that are automatically in scope. Here are those functions.

How to iterate over a Map in Kotlin (for loop)

Kotlin FAQ: How do I iterate over a Map in Kotlin?

Solution: Here’s an example of how to iterate over a Map in Kotlin using a for loop:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

for ((k,v) in map) {
    println("value of $k is $v")
}

Inside that for loop the variables k and v refer to the Map keys and values, respectively.

Example in the Kotlin REPL

Here’s what that looks like in the Kotlin REPL:

How to create an empty Scala Map

If you need to create an empty Map in Scala, the following examples show how to create empty immutable and mutable maps.

An empty immutable Map

You can use these approaches to create an empty immutable Scala Map:

val a = Map[Int, String]()
val a = Map.empty[Int, String]

Here’s what they look like in the REPL: