A list in Kotlin is an ordered collection of data(elements) with an unlimited list size. The size of the list can be increased based on elements. We have all usages List in Java as a beginner. A list in Kotlin is very useful because almost every data is processed and stored using a List. If you are a pro developer then you know about the benefits of using List and if you are a beginner then you are about to know using this tutorial. Using a list can significantly enhance your programming technique. In today’s tutorial, we will be going to learn about List initialization, inserting elements in the list, manipulating list items, and much more.
Lists are divided into 2 parts in Kotlin:
- Immutable List: Immutable lists are a type of list whose elements cannot be modified. This type of list has fast-ready operations and well optimized for mult-threaded operations.
123val fruitList = listOf("Apple", "Banana", "Cherry")println(fruitList) // Output: [Apple, Banana, Cherry] - Mutable List: In a mutable list we can perform add, update, and delete CURD operations. It is likely slower than an immutable list.
12345val mutableFruitList = mutableListOf("Apple", "Banana")mutableFruitList.add("Cherry")println(mutableFruitList) // Output: [Apple, Banana, Cherry]
Ultimate Kotlin List Guide: A Step-by-Step Tutorial for Beginners
- Integer List: In a mutable integer list, we can store integer-type values only.
123456789101112131415161718192021222324252627282930313233343536373839404142fun main() {// Using a MutableList instead of Listval intList: MutableList<Int> = mutableListOf(10, 20, 30, 40)// Accessing elementsprintln(intList[0]) // Output: 10// Iterating through the listprintln("\nBefore adding elements dynamically:")for (num in intList) {println(num)}// Adding elements dynamicallyintList.add(50)intList.add(60)// Iterating again to see the newly added elementsprintln("\nAfter adding elements dynamically:")for (num in intList) {println(num)}}// Output:10Before adding elements dynamically:10203040After adding elements dynamically:102030405060 - String List – Mutable
123456789fun main() {val stringList: MutableList<String> = mutableListOf("Apple", "Banana", "Cherry")// Adding elements dynamicallystringList.add("Date")println("String List: $stringList") // Output: String List: [Apple, Banana, Cherry, Date]} - Float List – Mutable
12345678fun main() {val floatList: MutableList<Float> = mutableListOf(1.5f, 2.3f, 4.8f)// Adding elements dynamicallyfloatList.add(6.4f)println("Float List: $floatList") // Output: Float List: [1.5, 2.3, 4.8, 6.4]} - Double Mutable List
12345678fun main() {val doubleList: MutableList<Double> = mutableListOf(10.12, 15.45, 8.95)// Adding elements dynamicallydoubleList.add(20.25)println("Double List: $doubleList") // Output: Double List: [10.12, 15.45, 8.95, 20.25]} - Boolean Mutable List
12345678fun main() {val boolList: MutableList<Boolean> = mutableListOf(true, false, true)// Adding elements dynamicallyboolList.add(false)println("Boolean List: $boolList") // Output: Boolean List: [true, false, true, false]} - Character Mutable list
123456789fun main() {val charList: MutableList<Char> = mutableListOf('A', 'B', 'C', 'D')// Adding elements dynamicallycharList.add('E')println("Character List: $charList") // Output: Character List: [A, B, C, D, E]} - Custom Model Mutable List: This list is mainly what we will be using in our Kotlin apps where we want to store different types of custom object-related data into our List. In this type of List first, we will create a Custom Model class in Kotlin as per that class we will store our data in List.
1234567891011121314151617181920212223242526272829303132// This Person class is same as custom Model class we created in Java.// There is no need to create Getter and Setter in data class.data class Person(val name: String, val age: Int)fun main() {// Mutable list of Person objectsval peopleList: MutableList<Person> = mutableListOf(Person("Tom", 30),Person("Bob", 25))// Adding elements dynamicallypeopleList.add(Person("Jay", 35))peopleList.add(Person("David", 40))// Getting single object elements.println(peopleList.get(0).age)println(peopleList.get(0).name)peopleList.forEach { println("${it.name}, Age: ${it.age}") }}// Output30TomTom, Age: 30Bob, Age: 25Jay, Age: 35David, Age: 40 - Nullable Mutable List: In a nullable list, we can store NULL values also but we have to pass ? (Question mark) Safe call operator. The? allow us to store a NULL value and make our variable type nullable.
12345678910fun main() {val nullableList: MutableList<Int?> = mutableListOf(10, null, 20)// Adding elements dynamicallynullableList.add(30)nullableList.add(null)println("Nullable List: $nullableList") // Output: Nullable List: [10, null, 20, 30, null]}
In the above example, we have covered most of the mutable list types we will use in our Kotlin program.
The most commonly used List Methods in Kotlin
In my examples, I am using the custom model class list. As a developer, we all know we use a List to store custom types of data which is associated with Model classes. For this example, I am creating a model class Person which has 2 member variables name and age. In Kotlin we do not have to define a constructor, getter & setter in the data class.
1 |
data class Person(val name: String, val age: Int) |
- add(): The add method in List in Kotlin adds an element to List.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))// 1. `add()`people.add(Person("Eva", 28))println("After adding Eva: $people")}data class Person(val name: String, val age: Int)// OutputAfter adding Eva: [Person(name=Jam, age=30), Person(name=Alice, age=25), Person(name=Bob, age=35), Person(name=Cris, age=20), Person(name=Eva, age=28)] - remove(): The remove method in List removes the first occurrence of the given element.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))people.remove(Person("Bob", 35))println("After removing Bob: $people")}data class Person(val name: String, val age: Int)// OutputAfter removing Bob: [Person(name=Jam, age=30), Person(name=Alice, age=25), Person(name=Cris, age=20)] - contains(): Check whether a List contains a specific element if yes then return True otherwise return False.
12345678910111213141516171819fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))println("Contains Charlie? ${people.contains(Person("Alice", 25))}")}data class Person(val name: String, val age: Int)// Output:Contains Charlie? true - get(): The get function in List returns us the item present on a specific Index position.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val firstPerson = people[0]println("First person: $firstPerson")}data class Person(val name: String, val age: Int)// Output:First person: Person(name=Jam, age=30) - size(): The size function returns the total length of the List.
123456789101112131415161718fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))println("Size of the list: ${people.size}")}data class Person(val name: String, val age: Int)// OutputSize of the list: 4 - clear(): Delete all elements from the list.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))people.clear()println("After clearing: $people")}data class Person(val name: String, val age: Int)// OutputAfter clearing: [] - sort(): To sort the list as per key.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))people.sortBy { it.age }println("Sorted by age: $people")}data class Person(val name: String, val age: Int)// OutputSorted by age: [Person(name=Cris, age=20), Person(name=Alice, age=25), Person(name=Jam, age=30), Person(name=Bob, age=35)] - filter(): The list filter function returns us a new List containing all the elements that match the given condition or predicate.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val adults = people.filter { it.age >= 30 }println("Adults (age >= 30): $adults")}data class Person(val name: String, val age: Int)// OutputAdults (age >= 30): [Person(name=Jam, age=30), Person(name=Bob, age=35)] - map(): The map function transforms the list elements according to the given function.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val names = people.map { it.name }println("Names of people: $names")}data class Person(val name: String, val age: Int)// OutputNames of people: [Jam, Alice, Bob, Cris] - forEach(): The for each is to print all the elements of the List one by one.
123456789101112131415161718192021222324fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))println("All people:")people.forEach { println(it) }}data class Person(val name: String, val age: Int)// OutputAll people:Person(name=Jam, age=30)Person(name=Alice, age=25)Person(name=Bob, age=35)Person(name=Cris, age=20) - joinToString(): It concatenates the elements of the List into a single string with a given Char or String.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val joinedNames = people.joinToString(", ") { it.name }println("Joined names: $joinedNames")}data class Person(val name: String, val age: Int)//OutputJoined names: Jam, Alice, Bob, Cris - find(): The find List function in Kotlin returns us the first condition matching element. If not found then return Null.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val firstAdult = people.find { it.age >= 30 }println("First adult: $firstAdult")}data class Person(val name: String, val age: Int)//OutputFirst adult: Person(name=Jam, age=30) - groupBy(): the groupBy method in the list makes groups of the element by a specified key.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val groupedByAge = people.groupBy { it.age >= 30 }println("Grouped by age >= 30: $groupedByAge")}data class Person(val name: String, val age: Int)// OutputGrouped by age >= 30: {true=[Person(name=Jam, age=30), Person(name=Bob, age=35)], false=[Person(name=Alice, age=25), Person(name=Cris, age=20)]} - any(): Checks if the element in the list matches the given predicate condition.
1234567891011121314151617181920fun main() {// Create a mutable list of Personvar people = mutableListOf(Person("Jam", 30),Person("Alice", 25),Person("Bob", 35),Person("Cris", 20))val hasMinors = people.any { it.age < 18 }println("Are there any minors? $hasMinors")}data class Person(val name: String, val age: Int)//OutputAre there any minors? false
I have tried my best to explain the most useful list method available in Kotlin. But there are a lot more also available in the official Kotlin documentation. You can read all of them from HERE.