In Kotlin, collections are used to store and manipulate groups of objects or data. There are several types of collections available in Kotlin, including:
- Lists – Ordered collections of elements that allow duplicates.
- Sets – Unordered collections of unique elements.
- Maps – Collections of key-value pairs, where each key is unique.
- Arrays – Fixed-size collections of elements with a specific type.
- Sequences – Lazily evaluated collections of elements that can be processed in a pipeline.
Here’s an example of creating and using a list in Kotlin:
Kotlin
val fruits = listOf( "apple" , "banana" , "orange" , "grape" )
println( "First fruit: ${fruits[0]}" )
println( "Last fruit: ${fruits.last()}" )
for (fruit in fruits) {
println(fruit)
}
val filtered = fruits.filter { it.startsWith( "a" ) }
println( "Filtered list: $filtered" )
|
In this example, we create a list of fruits using the listOf function, which takes a variable number of elements and returns an immutable list. We then demonstrate how to access elements in the list using indexing and the last function, and how to iterate over the list using a for loop. Finally, we use the filter function to create a new list containing only the elements that start with the letter “a”.
Kotlin’s other collection types can be used in similar ways, with specific functions and methods tailored to each type’s unique characteristics. By using these collection types, you can easily manage groups of data in your Kotlin programs.
Similar to Java Collections, Kotlin also introduced the concept of collections. A collection usually contains a number of objects of the same type and these objects in the collection are called elements or items. Kotlin Standard Library provides a rich set of tools for managing collections.
Types of Collections
In Kotlin collections are categorized into two forms.
- Immutable Collection
- Mutable Collection
1. Immutable Collection
It means that it supports only read-only functionalities and can not be modified its elements. Immutable Collections and their corresponding methods are:
- List – listOf() and listOf<T>()
- Set – setOf()
- Map – mapOf()
List – It is an ordered collection in which we can access elements or items by using indices – integer numbers that define a position for each element. Elements can be repeated in a list any number of times. We can not perform add or remove operations in the immutable list.
Kotlin program to demonstrate the immutable list:
Kotlin
fun main(args: Array<String>) {
val immutableList = listOf( "Mahipal" , "Nikhil" , "Rahul" )
for (item in immutableList){
println(item)
}
}
|
Output:
Mahipal
Nikhil
Rahul
Set – It is a collection of unordered elements also it does not support duplicate elements. It is a collection of unique elements. Generally, the order of set elements does not have a significant effect. We can not perform add or remove operations because it is an immutable Set.
Kotlin program to demonstrate the immutable set:
Kotlin
fun main(args: Array<String>) {
var immutableSet = setOf( 6 , 9 , 9 , 0 , 0 , "Mahipal" , "Nikhil" )
for (item in immutableSet){
println(item)
}
}
|
Output:
6
9
0
Mahipal
Nikhil
Map – Map keys are unique and hold only one value for each key, it is a set of key-value pairs. Each key maps to exactly one value. The values can be duplicates but keys should be unique. Maps are used to store logical connections between two objects, for example, a student ID and their name. As it is immutable its size is fixed and its methods support read-only access.
Kotlin program to demonstrate the immutable map:
Java
fun main(args : Array<String>) {
var immutableMap = mapOf( 9 to "Mahipal" , 8 to "Nikhil" , 7 to "Rahul" )
for (key in immutableMap.keys){
println(immutableMap[key])
}
}
|
Output:
Mahipal
Nikhil
Rahul
2. Mutable Collection
It supports both read and write functionalities. Mutable collections and their corresponding methods are:
- List – mutableListOf(),arrayListOf() and ArrayList
- Set – mutableSetOf(), hashSetOf()
- Map – mutableMapOf(), hashMapOf() and HashMap
List – Since mutable list supports read and write operation, declared elements in the list can either be removed or added.
Kotlin program to demonstrate the mutable list:
Kotlin
fun main(args : Array<String>) {
var mutableList = mutableListOf( "Mahipal" , "Nikhil" , "Rahul" )
mutableList[ 0 ] = "Praveen"
mutableList.add( "Abhi" )
for (item in mutableList){
println(item)
}
}
|
Output:
Praveen
Nikhil
Rahul
Abhi
Set – The mutable Set supports both read and write functionality. We can access add or remove elements from the collections easily and it will preserve the order of the elements.
Kotlin program to demonstrate the mutable set:
Kotlin
fun main(args: Array<String>) {
var mutableSet = mutableSetOf<Int>( 6 , 10 )
mutableSet.add( 2 )
mutableSet.add( 5 )
for (item in mutableSet){
println(item)
}
}
|
Output:
6
10
2
5
Map – It is mutable so it supports functionalities like put, remove, clear, etc.
Kotlin program to demonstrate the mutable map.
Kotlin
fun main(args : Array<String>) {
var mutableMap = mutableMapOf<Int,String>( 1 to "Mahipal" , 2 to "Nikhil" , 3 to "Rahul" )
mutableMap.put( 1 , "Praveen" )
mutableMap.put( 4 , "Abhi" )
for (item in mutableMap.values){
println(item)
}
}
|
Output:
Praveen
Nikhil
Rahul
Abhi
Here are some advantages and disadvantages of using collections in Kotlin:
Advantages:
- Improved code readability: Collections can make your code more readable and expressive by providing a higher-level abstraction for working with data.
- Better memory management: By using collections, you can avoid manual memory management and allow the Kotlin runtime to manage the memory for you.
- Increased efficiency: Kotlin’s collection types are designed for efficient storage and retrieval of data, making them ideal for large datasets or computationally intensive operations.
- Increased type safety: Collections provide type safety by ensuring that only elements of the correct type can be added to a collection.
Disadvantages:
- Performance overhead: Collections can add some performance overhead compared to working directly with primitive data types or arrays.
Memory usage: Depending on the size and complexity of your collections, they can use more memory than other data structures.
- Complexity: Collections can add complexity to your code, particularly if you need to perform complex operations on the data.
Overall, collections are a powerful tool for working with data in Kotlin, but they should be used judiciously based on the specific needs of your
- program. In general, collections are ideal for situations where you need to manage large or complex datasets, or when you need to perform sophisticated operations on the data.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Mar, 2023
Like Article
Save Article