Introduction

Hi friends, In this article, we will learn about the list and some important methods in Kotlin. The List is one of the important Collections in Kotlin. Collection refers to "a group of individual objects that represent a single entity". For example, "Collection of Students", "Collection of Books" etc. The list is one of the most frequently used Collections in almost every real-time project.

What is a List?

In Kotlin, we have Int, Double, Boolean, and String data types, but these data types can hold only one value. If we want to store more than one value, then we have to move to a list. A list is a collection of items, and a List maintains its insertion order. There are two types of lists in Kotlin:

ImmutableList in Kotlin

Immutable means we can not perform a write operation, which means we can not modify the list after creating it. We can only perform the read-only operation. We can create an immutable list using the listOf() method.

Example

    // Immutable List
    val fruitList= listOf("Apple", "Banana", "Orange", "Grapes", "Mango", "Strawberry", "Pineapple", "Watermelon", "Kiwi", "Peach")

    for (fruit in fruitList) {
        println(fruit)
    }

Output

Let's try to perform some operations on the Immutable List

fun main() {
    // Immutable List
    val fruitList= listOf("Apple", "Banana", "Orange", "Grapes", "Mango", "Strawberry", "Pineapple", "Watermelon", "Kiwi", "Peach")

    for (fruit in fruitList) {
        println(fruit)
    }

    fruitList.add("Guava") // Error
    fruitList.remove("Apple")// Error
}

Output

I got this above error because we can not modify the immutable list.

MutableList in Kotlin

To overcome the limitation of an immutable list, we can use the MutableList. Using MutableList, we can perform read and write operations. We can create an immutable list using the mutableListOf() method.

Example

fun main() {
    // mutable List
    val fruitList= mutableListOf("Apple", "Banana", "Orange", "Grapes", "Mango", "Strawberry", "Pineapple", "Watermelon", "Kiwi", "Peach")
    // Using mutableList, we can perform read and write operation
    fruitList.add("Guava")
    fruitList.remove("Apple")

    // print list
    for (fruit in fruitList) {
        println(fruit)
    }

}

Output

Important Method Used In List

Kotlin provides a variety of important methods for working with lists, which are part of the standard library. Here are some commonly used methods and operations for working with lists in Kotlin:

1. Accessing Elements

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")
    
    // Accessing elements
    println("Accessing elements:")
    println("First element: ${fruits.first()}")
    println("Last element: ${fruits.last()}")
    println("Element at index 2: ${fruits[2]}")
    
}

Output

2. Adding and Removing Elements

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")

    // Adding and removing elements
    println("Adding and removing elements:")
    fruits.add("grape")
    println("After adding 'grape': $fruits")

    fruits.remove("banana")
    println("After removing 'banana': $fruits")

    fruits.addAll(listOf("elderberry", "fig"))
    println("After adding multiple fruits: $fruits")

    fruits.removeAt(3)
    println("After removing element at index 3: $fruits")

}

Output

3. Filtering and Transformation

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")

    // Filtering and Transformation
    println("\nFiltering and Transformation:")
    val filteredFruits = fruits.filter { it.length <= 5 }
    println("Fruits with length <= 5: $filteredFruits")

    val uppercaseFruits = fruits.map { it.uppercase(Locale.getDefault()) }
    println("Uppercase fruits: $uppercaseFruits")
}

Output

4. Sorting

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")

    // Sorting
    println("Sorting:")

    fruits.sort()
    println("Sorted in ascending order: $fruits")

    fruits.sortDescending()
    println("Sorted in descending order: $fruits")

    fruits.sortByDescending { it.length }
    println("Sorted in descending order of length: $fruits")

}

Output

5. Checking and Manipulating List Properties

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")

    // Checking and Manipulating List Properties
    println("Checking and Manipulating List Properties:")
    println("Is the list empty? ${fruits.isEmpty()}")
    println("List size: ${fruits.size}")

}

Output

6. Finding Elements

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")

    // Finding Elements
    println("\nFinding Elements:")
    println("Does the list contain 'banana'? ${fruits.contains("banana")}")
    println("Index of 'cherry': ${fruits.indexOf("cherry")}")
    println("Last index of 'date': ${fruits.lastIndexOf("date")}")

}

Output

7. Converting Lists

Example

fun main() {
    // Creating a mutable list
    val fruits = mutableListOf("apple", "banana", "cherry", "date")

    // Converting Lists
    val immutableFruits = fruits.toList()
    val mutableFruits = immutableFruits.toMutableList()
    println("Converting Lists:")
    println("Immutable list: $immutableFruits")
    println("Mutable list: $mutableFruits")
}

Output

Conclusion

In this article, we have seen how to use List and its method in Kotlin. Thanks for reading, and hope you like it. If you have any suggestions or queries about this article, please share your thoughts. You can read my other articles by clicking here.

Happy learning, friends!