Kotlin functions to create Lists, Maps, and Sets
[toc]
With Kotlin you can create lists, maps, and sets with standard functions that are automatically in scope. Here are those functions.
[toc]
With Kotlin you can create lists, maps, and sets with standard functions that are automatically in scope. Here are those functions.
[toc]
Somewhere in mid-2017 I started working on a Kotlin programming book, but then I had to get away from it to work on other things. When I got back to it recently I looked around and felt like the world didn’t need another “Introduction to Kotlin” book — there are a couple of good ones out there, including Kotlin in Action, and the kotlinlang.org documentation is excellent — so I decided to ditch the project completely.
But then when I started writing some Kotlin code again I realized that what I really needed was a quick reference. I didn’t want to have to dig through a tutorial book or website to find what I need, I just wanted something like a large cheat sheet where I could quickly find the Kotlin syntax and examples for whatever I was working on at that moment. So I decided to strip down what I had already written and create both a book and a Kotlin Quick Reference website.
Kotlin FAQ: How do I iterate over the elements in a Map
in Kotlin?
Here’s an example that shows how to iterate over the elements in a Kotlin Map
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") }
As a quick note today, if you ever need some examples of how the Kotlin collections methods work, I hope these examples are helpful.
First, here’s some sample data:
val a = listOf(10, 20, 30, 40, 10)
val names = listOf("joel", "ed", "chris", "maurice")
Tonight (December 2, 2018) I’m releasing my latest book, Kotlin Quick Reference.
This page is a work in progress, but if you need to create a secondary class constructor in Kotlin, I hope it’s helpful.
I thought about writing a “functional programming in Kotlin” book, but I think that Kotlin and Scala are similar enough that Functional Programming, Simplified will be good for Kotlin programmers as well as Scala programmers.
As a quick note, here’s an example of how to use the Kotlin sortedWith
syntax with an anonymous function (lambda). Given this list of integers:
val list = listOf(7,3,5,9,1,3)
Here’s an example of how to use sortedWith
using a Comparator
and lambda:
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]}