Find Last Index of Element in Kotlin ArrayList | Kotlin ArrayList lastIndexOf Function

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

The lastIndexOf function in Kotlin is used to find the index of the last occurrence of a specified element in an ArrayList. This function is part of the Kotlin standard library and provides a convenient way to search for elements in a list from the end to the beginning and retrieve their positions.

Table of Contents

  1. Introduction
  2. lastIndexOf Function Syntax
  3. Understanding lastIndexOf
  4. Examples
    • Basic Usage
    • Finding the Last Index of a String
    • Handling Non-Existent Elements
  5. Real-World Use Case
  6. Conclusion

Introduction

The lastIndexOf function allows you to search for a specified element in an ArrayList and return the index of its last occurrence. If the element is not found, the function returns -1.

lastIndexOf Function Syntax

The syntax for the lastIndexOf function is as follows:

fun <T> ArrayList<T>.lastIndexOf(element: T): Int

Parameters:

  • element: The element to be searched for in the list.

Returns:

  • Int: The index of the last occurrence of the specified element, or -1 if the element is not found.

Understanding lastIndexOf

The lastIndexOf function searches through the ArrayList from the end to the beginning, looking for the specified element. It returns the index of the last occurrence of the element. If the element is not present in the list, the function returns -1.

Examples

Basic Usage

To demonstrate the basic usage of lastIndexOf, we will create an ArrayList and find the last index of specific elements.

Example

fun main() {
    val numbers = arrayListOf(10, 20, 30, 40, 50, 20, 30)
    println("Last index of 20: ${numbers.lastIndexOf(20)}")
    println("Last index of 30: ${numbers.lastIndexOf(30)}")
    println("Last index of 60: ${numbers.lastIndexOf(60)}")
}

Output:

Last index of 20: 5
Last index of 30: 6
Last index of 60: -1

Finding the Last Index of a String

This example shows how to use lastIndexOf to find the last index of a string in an ArrayList.

Example

fun main() {
    val fruits = arrayListOf("Apple", "Banana", "Cherry", "Apple", "Date")
    println("Last index of 'Apple': ${fruits.lastIndexOf("Apple")}")
    println("Last index of 'Date': ${fruits.lastIndexOf("Date")}")
    println("Last index of 'Elderberry': ${fruits.lastIndexOf("Elderberry")}")
}

Output:

Last index of 'Apple': 3
Last index of 'Date': 4
Last index of 'Elderberry': -1

Handling Non-Existent Elements

This example demonstrates how to handle cases where the element is not present in the list.

Example

fun main() {
    val colors = arrayListOf("Red", "Green", "Blue", "Red")
    val index = colors.lastIndexOf("Yellow")

    if (index != -1) {
        println("Last index of 'Yellow': $index")
    } else {
        println("'Yellow' is not in the list.")
    }
}

Output:

'Yellow' is not in the list.

Real-World Use Case

Searching for Usernames in a List

In real-world applications, the lastIndexOf function can be used to search for specific usernames in a list of users, especially if usernames can appear multiple times.

Example

data class User(val id: Int, val name: String, val email: String)

fun main() {
    val users = arrayListOf(
        User(1, "Alice", "alice@example.com"),
        User(2, "Bob", "bob@example.com"),
        User(3, "Alice", "alice2@example.com")
    )

    val userName = "Alice"
    val index = users.lastIndexOf(users.findLast { it.name == userName })

    if (index != -1) {
        println("Last index of user 'Alice': $index")
    } else {
        println("User 'Alice' is not in the list.")
    }
}

Output:

Last index of user 'Alice': 2

Conclusion

The lastIndexOf function in Kotlin is a simple and effective way to find the index of the last occurrence of a specified element in an ArrayList. It allows you to search for elements from the end to the beginning and retrieve their positions, making it useful for various applications, including data searching and validation. 

By understanding and using the lastIndexOf function, you can effectively manage and manipulate ArrayList collections in your Kotlin applications.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare