Is there a way to add an 'index' (in the DB sense) to a collection?

So say I have a list of all the train stations in the world, like

data class Station(
  val id: Int,
  val name: Name,
  val country: Country,

this list might get pretty large, and some common operations on this list (“get all stations named ‘Tokyo’” or “get all stations in Germany”) would each require scanning the full list.

Knowing the use cases, of course you could generate a series of maps like val stationsByCountry: Map<Country, List<Station>>. But doing so requires manually constructing them, and is a bit of a nuisance.

The interface I would want is something like:

val stations = stationList
   .indexBy { }
   .indexBy { }
   .indexBy { }
println(stations.searchFor("Germany"){ })

with indexBy returning a new collection that internally stores index data for lookup.

I understand there are complications with this exact interface (finding the index for the selector in the search, for example), but something like this should be doable. Has it been done somewhere? Is it something others might find generally useful?

You’re describing a database.
If you have a list of stations in memory already constructing those maps is rather cheap, groupBy - Kotlin Programming Language groupBy does exactly that.

However usually one uses a relational database - so that you don’t have to keep the whole thing in memory - and some library to read such database. Java is full of options JPA/Hibernate or Jooq to mention 2.