0
0
Android Kotlinmobile~5 mins

Collections (List, Map, Set) in Android Kotlin

Choose your learning style9 modes available
Introduction

Collections help you store and organize multiple items together. They make it easy to work with groups of data in your app.

When you want to keep a list of names or items in order.
When you need to find a value by a key, like a phone number by a contact name.
When you want to store unique items without duplicates, like a set of tags.
When you want to loop through many items to show them on the screen.
When you want to add or remove items easily from a group.
Syntax
Android Kotlin
val list: List<Type> = listOf(item1, item2, item3)
val mutableList: MutableList<Type> = mutableListOf(item1, item2)

val map: Map<KeyType, ValueType> = mapOf(key1 to value1, key2 to value2)
val mutableMap: MutableMap<KeyType, ValueType> = mutableMapOf(key1 to value1)

val set: Set<Type> = setOf(item1, item2)
val mutableSet: MutableSet<Type> = mutableSetOf(item1)

List keeps items in order and can have duplicates.

Map stores key-value pairs for quick lookup by key.

Set stores unique items without duplicates.

Mutable collections let you add or remove items after creation.

Examples
A list of fruits with duplicates allowed.
Android Kotlin
val fruits: List<String> = listOf("Apple", "Banana", "Apple")
A map to find phone numbers by name.
Android Kotlin
val phoneBook: Map<String, String> = mapOf("Alice" to "1234", "Bob" to "5678")
A set that keeps only unique tags, so "kotlin" appears once.
Android Kotlin
val uniqueTags: Set<String> = setOf("kotlin", "android", "kotlin")
An empty list with no items.
Android Kotlin
val emptyList: List<Int> = listOf()
Sample App

This program shows how to create and change a list, map, and set. It prints the collections before and after adding new items.

Android Kotlin
fun main() {
  val shoppingList: MutableList<String> = mutableListOf("Milk", "Eggs")
  println("Before adding: $shoppingList")
  shoppingList.add("Bread")
  println("After adding Bread: $shoppingList")

  val contacts: MutableMap<String, String> = mutableMapOf("John" to "111-222")
  println("Contacts before update: $contacts")
  contacts["Mary"] = "333-444"
  println("Contacts after adding Mary: $contacts")

  val colors: MutableSet<String> = mutableSetOf("Red", "Green")
  println("Colors before adding Red again: $colors")
  colors.add("Red")
  println("Colors after adding Red again: $colors")
}
OutputSuccess
Important Notes

Lists keep order and allow duplicates; sets do not allow duplicates and have no order.

Maps let you find values fast by their keys.

Mutable collections let you change items; immutable ones do not.

Adding an existing item to a set does nothing because sets keep unique items.

Summary

Use List to keep ordered items, duplicates allowed.

Use Map to store key-value pairs for quick lookup.

Use Set to store unique items without duplicates.