Welcome to our comprehensive guide about Kotlin List!
If you're learning how to program with Kotlin, you should familiarize yourself with the Kotlin List. A list in Kotlin is an ordered collection of elements. Kotlin offers both mutable lists (MutableList) and read-only lists (List). Mutable lists are open to structural changes, like adding, removing, or updating elements. On the contrary, read-only lists are fixed and merely facilitate the retrieval of elements.
1// Kotlin program to demonstrate mutable lists 2fun main() { 3 val mutableList = mutableListOf(1, 2, 3) 4 mutableList.add(4) // This is a valid operation 5 println(mutableList) // Outputs: [1, 2, 3, 4] 6}
There’s more to the Kotlin list than what meets the eye. Lists in Kotlin predominantly derive their characteristics from the Collection interface. Specifically, the List interface governs the behavior of lists in Kotlin, making it a foundation of the topic.
Now that fundamentals of what constitutes a list Kotlin are clear, we shall move on to how to create and work with Kotlin lists, including how to manipulate elements at a specific position.
1// Kotlin program to demonstrate list creation. 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 println(numbers) // Outputs: [1, 2, 3, 4, 5] 5}
Creating a Kotlin list is straightforward. All you need is the listOf() or mutableListOf(), and you can create your list containing elements of the same type. Here's how to do it:
1// Kotlin program to demonstrate list creation 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 println(numbers) // Outputs: [1, 2, 3, 4, 5] 5 6 val mutableList = mutableListOf("A", "B", "C") 7 println(mutableList) // Outputs: [A, B, C] 8}
When creating a list Kotlin, keep in mind read-only lists cannot accommodate more elements or changes after their declaration. Lists can hold null elements too, but remember that adding them can make your code prone to NullPointerException.
Apart from Lists, arrays also play an indispensable role in Kotlin. A Kotlin ArrayList is a dynamic array with a variable number of elements, essentially rendering it as a mutable list. You can add elements, or even remove elements effortlessly. Just like Lists, ArrayList in Kotlin can also store null elements.
Element insertion in an ArrayList can be done at any specific position, shifting subsequent elements to the right.
1// Kotlin program to demonstrate Kotlin ArrayList 2fun main() { 3 val arrayList = arrayListOf(2, 4, 6, 8) 4 println(arrayList) // Outputs: [2, 4, 6, 8] 5 6 // Adding element to ArrayList 7 arrayList.add(10) 8 println(arrayList) // Outputs: [2, 4, 6, 8, 10] 9 10 // Removing an element from ArrayList 11 arrayList.remove(4) 12 println(arrayList) // Outputs: [2, 6, 8, 10] 13}
Keep in mind that ArrayLists are performance-optimized for write operations. Using them for read-heavy segments might be a bit of an overkill.
Kotlin provides a robust set of functions to enhance your list manipulation capabilities. These functions allow for efficient retrieval, transformation, and filtering of list elements, making your code more expressive and concise.
You can retrieve elements by their specified index, or use functions like first() and last() to get the first or last element, respectively.
1// Kotlin program to retrieve the first element 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 println(numbers[0]) // Outputs: 1 5 println(numbers.first()) // Outputs: 1 6 println(numbers.last()) // Outputs: 5 7}
The filter() function returns a list containing elements that match a given predicate. This is useful for creating sublists based on specific conditions.
1// Kotlin program demonstrating the filter function 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 val evenNumbers = numbers.filter { it % 2 == 0 } 5 println(evenNumbers) // Outputs: [2, 4] 6}
Kotlin provides several functions for transforming lists, such as map, flatMap, and associate.
1// Kotlin program demonstrating the map function 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 val doubled = numbers.map { it * 2 } 5 println(doubled) // Outputs: [2, 4, 6, 8, 10] 6}
You can convert a list to other collections, such as a set or an array. This can be useful for eliminating duplicates or working with APIs that require different types.
1// Kotlin program to convert a list to a set 2fun main() { 3 val numbers = listOf(1, 2, 2, 3, 4, 4, 5) 4 val uniqueNumbers = numbers.toSet() 5 println(uniqueNumbers) // Outputs: [1, 2, 3, 4, 5] 6}
1// Kotlin program to convert a list to an array 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 val numberArray = numbers.toTypedArray() 5 println(numberArray.joinToString()) // Outputs: 1, 2, 3, 4, 5 6}
The toTypedArray() function converts a list to a vararg, enabling you to pass list elements to a function that accepts varargs.
1// Kotlin program demonstrating list to vararg conversion 2fun printNumbers(vararg numbers: Int) { 3 for (number in numbers) { 4 println(number) 5 } 6} 7 8fun main() { 9 val numbers = listOf(1, 2, 3) 10 printNumbers(*numbers.toTypedArray()) 11 // Outputs: 12 // 1 13 // 2 14 // 3 15}
The any() function checks if any elements in the list match a given condition. This is useful for quick validation checks.
1// Kotlin program demonstrating the any function 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 val hasEven = numbers.any { it % 2 == 0 } 5 println(hasEven) // Outputs: true 6}
The associateBy or associateWith functions convert a list to a map, enabling you to define key-value pairs based on list elements.
1// Kotlin program demonstrating the associateBy function 2data class Person(val name: String, val age: Int) 3 4fun main() { 5 val people = listOf(Person("Alice", 30), Person("Bob", 25)) 6 val peopleByName = people.associateBy { it.name } 7 println(peopleByName) // Outputs: {Alice=Person(name=Alice, age=30), Bob=Person(name=Bob, age=25)} 8}
Kotlin provides a wide array of functions to manipulate lists effectively. Utilizing these functions allows you to perform complex operations with minimal code, making your Kotlin programming experience more enjoyable and productive.
Kotlin provides a variety of methods for working with lists. These include ‘add()’, ‘remove()’, and their respective variations, to undertake various operations on the Kotlin arraylist. They serve to enhance the flexibility and dynamism of lists.
For instance, to add elements to the list:
1// Kotlin program to add elements to a mutable list 2fun main() { 3 val list = mutableListOf("Element1", "Element2") 4 list.add("Element3") 5 println(list) // Outputs: [Element1, Element2, Element3] 6}
Just as you can add elements, you can also remove elements from the list.
1// Kotlin program to remove elements from a list 2fun main() { 3 val list = mutableListOf("Element1", "Element2", "Element3") 4 list.remove("Element2") 5 println(list) // Outputs: [Element1, Element3] 6}
You can also modify a specific element by referencing its index.
1// Kotlin program illustrating modification of elements in a list 2fun main() { 3 val list = mutableListOf("Element1", "Element2", "Element3") 4 list[1] = "ModifiedElement" 5 println(list) // Outputs: [Element1, ModifiedElement, Element3] 6}
You can also replace elements in a list with a specified value using the set() or fill() methods.
Manipulating lists allows more flexibility and control over your data in Kotlin.
The subList() function, known as abstract fun sublist in the Kotlin language, is used to retrieve a range, or rather specified range of elements, from the original list. This functionality can be leveraged to work with only a portion of the list without affecting the other elements.
Here's how to use the subList() function:
1// Kotlin program demonstrating sublist 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 println(numbers.subList(1, 4)) // Outputs: [2, 3, 4] 5}
As demonstrated, the subList() function offers a way out when we only consider a fraction of the list for processing. The result is a new list from the given index range.
Both Kotlin List and Kotlin ArrayList are ordered collections of elements and provide similar functionality to a large extent. Kotlin List, being part of the Kotlin Standard Library, is primarily concerned with an ordered collection of read-only elements. On the other hand, Kotlin ArrayList, a part of Java's standard collections framework, acts as a dynamically sized array (or what we term as mutable list) that allows structural changes – such as adding or removing elements.
1// Kotlin program illustrating List vs. ArrayList 2fun main() { 3 val list = listOf("Element1", "Element2") 4 // list.add("Element3") // This would return an error! 5 6 val arrayList = arrayListOf("Element1", "Element2") 7 arrayList.add("Element3") 8 println(arrayList) // Outputs: [Element1, Element2, Element3] 9}
While working with Kotlin, it's recommended to use List for read-intensive tasks and ArrayList when structural changes are involved.
A LinkedList in Kotlin is a collection that maintains an ordered sequence of elements. It allows for efficient insertion and deletion at both ends of the list.
Getting the first element could be as simple as using list.first(). The first() function gives the first element of the list. For an empty list, it throws an exception.
1// Kotlin program illustrating how to get the first item of a list 2fun main() { 3 val numbers = listOf(1, 2, 3, 4, 5) 4 println(numbers.first()) // Outputs: 1 5}
An even more advanced function, firstOrNull() can be used which returns null for an empty list instead of throwing an exception.
Working with a 'list in Kotlin' would be easier and more effective if you follow these best practices:
1// Kotlin program illustrating the use of read-only lists 2fun main() { 3 val list = listOf("read", "only", "list") 4 println(list) // Outputs: [read, only, list] 5}
1// Kotlin program illustrating the use of abstract functions 2fun main() { 3 val list1 = listOf(1, 2, 3, 4, 5) 4 val list2 = listOf(2, 4) 5 println(list1.containsAll(list2)) // Outputs: true 6}
1// Kotlin program demonstrating the use of list iterators 2fun main() { 3 val list = listOf("A", "B", "C") 4 for (element in list) { 5 println(element) 6 } 7 // A 8 // B 9 // C 10}
Prefer 'specified index' for Access: To access list elements, using the index is more performant and straightforward.
Beware of Nullable Types: Nullable types can lead to NullPointerExceptions; it is best to avoid them if you can.
Do not reinvent the wheel: Utilize the functions provided: Kotlin provides various functions. Whether it’s checking the number of elements with size, or if an element exists with contains, Kotlin has got it all covered.
With these best practices, you'll find crafting solutions with Kotlin Lists much more comfortable and effective.
From creating a fundamental list in Kotlin to exploring the concepts of elements matching, specified element, and specified index, this guide aims to make you confident with Lists in Kotlin.
Whether you're mapping the elements, fetching the first element, performing sublist operations, or deciding between a mutable and read-only list, Kotlin has abundant pre-built function and flexibility to help you out. Always follow best practices and keep experimenting to sharpen your Kotlin skills. And remember, the more you work with Kotlin, the more interesting it becomes.
Happy Kotlin Programming!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.