Library contents

Kotlin List.indexOf and lastIndexOf

Find both ends of a repeated stop in a travel itinerary.

A simple example

List.indexOf and lastIndexOf

  1. Start with A, B, A
  2. Do this Locate the first and last A
  3. Result First and third positions
The first match occurs at the beginning and the second at the end.

Syntax

Kotlin syntax
stops.lastIndexOf(stop)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Find both visits to the market

A circular bus route visits the market on both the outward and return journeys. A timetable editor needs the first and last positions of the market to label the two visits correctly.

From the programval stops = listOf("Depot", "Market", "Park", "Market")
Result1 and 3
Lesson.kt
fun main() {
    val stops = listOf("Depot", "Market", "Park", "Market")
    println("${stops.indexOf("Market")} and ${stops.lastIndexOf("Market")}")
}
Output
1 and 3

The zero-based positions show Market on the outward trip at one and on the return trip at three.

Advertisements

Locate a transfer stop

A bus calls at Hill twice on its circular route. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.

GivenLake · Hill · Mill · Hill
Worked result1

Find a returned item

A desk checks the earliest entry marked Pen. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.

GivenPen · Ruler · Pen
Worked result0

What to watch for

Both lookups return -1 when there is no matching stop.

Documentation for List.indexOf and lastIndexOf