Kotlin ArrayList : An Essential Guide for Beginners
Kotlin’s ArrayList offers flexibility and convenience when dealing with collections of data. In this guide, we will explore the features, and examples of Kotlin ArrayList.
What is an ArrayList?
An ArrayList is an implementation of the MutableList interface. It represents a dynamic sized array that can grow or shrink as elements are added or removed. Unlike regular arrays, which have a fixed size, ‘ArrayList’ provides the ability to store and manipulate collections of elements without worrying about predefined lengths.
How to create an ArrayList in Kotlin?
To create an ArrayList in Kotlin, you can use ArrayList() constructor or the arrayListOf() function.
Let’s create an ArrayList using ArrayList() constructor :
val veg = ArrayList<String>()
veg.add("Tomato")
Kotlin ArrayList Example Program:
Here’s an example of creating an ArrayList and initializing it with some elements:
fun main()
{
val veg = ArrayList<String>()
veg.add("Tomato")
veg.add("Cabbage")
veg.add("Bitter Gourd")
println(veg)
}
Output
[Tomato, Cabbage, Bitter Gourd]
Alternatively, you can use the arrayListOf() function.
var os = arrayListOf("Android", "iOS","MacOS")
arrayListOf() Function Example
fun main()
{
val os = arrayListOf("Android", "iOS","MacOS")
os.add("Linus")
os.add("iPadOS")
println(os)
}
Output
[Android, iOS, MacOS, Linus, iPadOS]
Adding and Removing Elements from Kotlin ArrayList
ArrayList provides various methods for adding and removing elements dynamically. Some commonly used functions include add(), addAll(), remove(), and removeAt().
Adding a single element to an ArrayList
val os = arrayListOf("Android", "iOS","MacOS")
os.add("Linus")
Add a collections of elements
fun main()
{
val os = arrayListOf("Android", "iOS","MacOS")
os.addAll(listOf("wearOS","Windows XP"))
println(os)
}
Output
[Android, iOS, MacOS, wearOS, Windows XP]
Remove a specific element from an ArrayList
os.remove("Android")
println(os)
[iOS, MacOS, wearOS, Windows XP]
Remove an element at a specific index
os.removeAt(2)
println(os)
[iOS, MacOS, iPadOS, wearOS, Windows XP]
Program
Main.kt
Open Kotlin Play ground and Write the following program:
fun main()
{
val os = arrayListOf("Android", "iOS","MacOS")
os.add("Linus")
os.add("iPadOS")
println(os)
os.addAll(listOf("wearOS","Windows XP"))
println(os)
// Remove an element
os.remove("Android")
println(os)
// Removes an element at a specific index
os.removeAt(2)
println(os)
}
Accessing and Modifying Elements
You can access individual elements of an ArrayList using the index operator [] and modify them directly.
fun main()
{
val os = arrayListOf("Android", "iOS","MacOS")
println(os)
val firstOS = os[1]
println(firstOS)
os[1] = "Linux"
println(os)
}
[Android, iOS, MacOS]
iOS
[Android, Linux, MacOS]
Iterating Over an ArrayList
ArrayList can be easily iterated using various looping constructs like the for loop or the forEach() function.
for loop :
fun main()
{
val os = arrayListOf("Android", "iOS","MacOS")
for (name in os)
{
println(name)
}
}
Android
iOS
MacOS
forEach:
fun main()
{
val os = arrayListOf("Android", "iOS","MacOS")
os.forEach { item ->
println(item)
}
}
Other Useful ArrayList Functions
Kotlin’s ArrayList provides a range of functions for working with lists efficiently. Some noteworthy functions include contains(), size, isEmpty(), clear(), indexOf(), lastIndexOf(), and subList()
Checks if “iOS” exists
val os = arrayListOf("Android", "iOS","MacOS", "Linux", "Solaris")
val checkOS = os.contains("iOS") // Checks if "iOS" exists
println(checkOS)// true
Retrieve the size of the ArrayList
val size = os.size // Retrieves the size of the ArrayList
println(size)
Check if the ArrayList is empty
val isEmpty = os.isEmpty() // Checks if the ArrayList is empty
println(isEmpty)
Retrieve the index of “MacOS”
val index = os.indexOf("MacOS") // Retrieves the index of "MacOS"
println(index)
Retrieve a portion of the ArrayList
val subList = os.subList(1, 3) // Retrieves a portion of the ArrayList
println(subList)
Clear all elements from the ArrayList
os.clear()
Kotlin ArrayList vs. Array
While arrays offer fixed sizes and lower memory overhead, ArrayList provides dynamic resizing and flexibility. Arrays are more suitable when the size of the collection is known and doesn’t change, whereas ArrayList shines when working with dynamic data.
Kotlin ArrayList Remove Duplicated Elements
Example :
fun main() {
val numbers = arrayListOf(1, 2, 3, 4, 2, 3, 5,5, 61, 4, 7, 8, 81, 9,9)
println("Original ArrayList:")
println(numbers)
val uniqueNumbers = ArrayList<Int>()
val set = HashSet<Int>()
for (number in numbers) {
if (set.add(number)) {
uniqueNumbers.add(number)
}
}
println("ArrayList with Duplicates Removed:")
println(uniqueNumbers)
}
Original ArrayList:
[1, 2, 3, 4, 2, 3, 5, 5, 61, 4, 7, 8, 81, 9, 9]
ArrayList with Duplicates Removed:
[1, 2, 3, 4, 5, 61, 7, 8, 81, 9]
In this example, we have an ArrayList called numbers that contains some duplicate elements. We want to remove these duplicate items and obtain a new ArrayList called uniqueNumbers without any duplicates.
We create an empty HashSet called set, which will help us keep track of unique elements. Then, we iterate over each element in the numbers ArrayList.