harish
harish

Reputation: 295

How to find key index in a map?

I have a Map and add index in map by using

val indexByColName = sorted.view.zipWithIndex.toMap

How do I find index for a specific key?

Upvotes: 0

Views: 996

Answers (2)

elm
elm

Reputation: 20415

Method indexWhere for instance in Array provides this semantics as follows,

implicit class keyIndexing[A,B](val m: Map[A,B]) extends AnyVal {
  def keyIndex(key: A, value: B) = {
    m.toArray.indexWhere{ case (k,v) => key == k && value == v }
  }
}

Then for

val sorted = Map("a" -> 10, "b" -> 11, "c" -> 12)

scala> sorted.keyIndex("a",10)
res15: Int = 0

and for a non matching (or non existing) key and value,

scala> sorted.keyIndex("a",11)
res16: Int = -1

scala> sorted.keyIndex("z",11)
res19: Int = -1

Upvotes: 1

Brian
Brian

Reputation: 20285

Defining sorted and showing the output you want would help but I think this might do it.

scala> val sorted = Map("zero" -> 0, "one" -> 1, "two" -> 2)
sorted: scala.collection.immutable.Map[String,Int] = Map(zero -> 0, one -> 1, two -> 2)

scala> val indexByColName =sorted.view.zipWithIndex.toMap
indexByColName: scala.collection.immutable.Map[(String, Int),Int] = Map((zero,0) -> 0, (one,1) -> 1, (two,2) -> 2)

scala> indexByColName.get(("zero", 0)).get
res1: Int = 0

scala> indexByColName.get(("two", 2)).get

res3: Int = 2

Upvotes: 1

Related Questions