In this tutorial, we aim to teach you the specifics of Lists, Sets, and Maps in Kotlin, which are fundamental data structures used to store and manipulate data in programming.
By the end of this guide, you will:
Prerequisites: Basic understanding of Kotlin syntax and programming concepts.
A List in Kotlin is an ordered collection of items. Each item in the list has an index, starting from 0.
To create a list, you can use the listOf
function:
val names = listOf("John", "Sarah", "Mark")
A Set in Kotlin is an unordered collection of unique items. It does not contain duplicate items.
To create a set, you can use the setOf
function:
val uniqueNumbers = setOf(1, 2, 3, 1)
Note that the duplicate 1
is only stored once in the set.
A Map in Kotlin is a collection of key-value pairs. Each key is unique and is associated with exactly one value.
To create a map, you can use the mapOf
function:
val ages = mapOf("John" to 25, "Sarah" to 30)
Here's an example of creating and manipulating a list in Kotlin:
val numbers = mutableListOf(1, 2, 3, 4, 5) // mutable list allows modifications
numbers.add(6) // adds the number 6 to the end of the list
println(numbers) // prints [1, 2, 3, 4, 5, 6]
Here's an example of creating and manipulating a set in Kotlin:
val set = mutableSetOf(1, 2, 3, 1) // mutable set allows modifications
set.add(4) // adds the number 4 to the set
println(set) // prints [1, 2, 3, 4]
Here's an example of creating and manipulating a map in Kotlin:
val map = mutableMapOf("John" to 25, "Sarah" to 30) // mutable map allows modifications
map["Mark"] = 35 // adds a new key-value pair to the map
println(map) // prints {John=25, Sarah=30, Mark=35}
We've covered the basics of Lists, Sets, and Maps in Kotlin. You've learned how to create these data structures, add items to them, and print their contents.
The next steps for your learning could be understanding how to remove items from these collections, how to sort them, and how to search for specific items.
Additional resources:
- Kotlin Official Documentation
Solution:
kotlin
val movies = mutableListOf("Inception", "Interstellar", "The Dark Knight")
println(movies) // prints [Inception, Interstellar, The Dark Knight]
movies.add("Dunkirk")
println(movies) // prints [Inception, Interstellar, The Dark Knight, Dunkirk]
Solution:
kotlin
val numbers = mutableSetOf(1, 2, 3, 4, 5)
println(numbers) // prints [1, 2, 3, 4, 5]
numbers.add(3)
println(numbers) // still prints [1, 2, 3, 4, 5] because sets don't allow duplicates
Solution:
kotlin
val ages = mutableMapOf("John" to 25, "Sarah" to 30)
println(ages) // prints {John=25, Sarah=30}
ages["Mark"] = 35
println(ages) // prints {John=25, Sarah=30, Mark=35}