1 - Intro
1 - Intro
Kotlin Collections
Read Discuss Courses Practice
Kotlin
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.
Surfcoin Open
Types of Collections
In Kotlin collections are categorized into two forms.
1. Immutable Collection
2. 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:
Kotlin
Output:
Mahipal
Nikhil
Rahul
Kotlin
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.
Java
Output:
Mahipal
Nikhil
Rahul
2. Mutable Collection
It supports both read and write functionalities. Mutable collections and their
corresponding methods are:
List – Since mutable list supports read and write operation, declared elements
in the list can either be removed or added.
Kotlin
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.
Output:
6
10
2
5
Kotlin
Output:
Praveen
Nikhil
Rahul
Abhi
Advantages:
1. Improved code readability: Collections can make your code more readable
and expressive by providing a higher-level abstraction for working with
data.
2. Better memory management: By using collections, you can avoid manual
memory management and allow the Kotlin runtime to manage the memory
for you.
3. 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.
4. Increased type safety: Collections provide type safety by ensuring that only
elements of the correct type can be added to a collection.
Disadvantages:
Similar Reads