Finding the index of a specific SortedMap

272 views Asked by At

I have a SortedMap of the type:

data: SortedMap[Long, SortedMap[String, Double]]

How can I find the index of a specific key.

For example:

data = (1L -> ("a" -> 1.), 2L -> ("b" -> 1., "c" -> 2.), 3L -> ("b" -> 1.))

I want to find the index of key 2L (the result should be 1).

2

There are 2 answers

0
elm On BEST ANSWER

Found this approach based in an iterator over keys that avoids indexing intermediate collections as follows,

data.keysIterator.indexWhere(_ == 2)

For ease of use consider this implicit,

implicit class RichSortedMap[A,B](val m: SortedMap) extends AnyVal {
  def keyIndexWhere(k: A) = m.keysIterator.indexWhere( _ == k )
}

and so you can use it as follows,

data.keyIndexWhere(2)
1
Michael Zajac On

You could use zipWithIndex to pair each key-value with it's index, then use collectFirst to find the pair with the correct key and extract the index. This will return Option[Int] (so None if the key is not found).

val data: SortedMap[Long, SortedMap[String, Double]] = SortedMap(
    1L -> SortedMap("a" -> 1.0), 
    2L -> SortedMap("b" -> 1.0, "c" -> 2.0), 
    3L -> SortedMap("b" -> 1.0)
)

def findIndex(data: SortedMap[Long, SortedMap[String, Double]], key: Long): Option[Int] = 
    data.zipWithIndex.collectFirst { case ((`key` , _), i) => i }

scala> findIndex(data, 1L)
res16: Option[Int] = Some(0)

scala> findIndex(data, 2L)
res17: Option[Int] = Some(1)

scala> findIndex(data, 10L)
res18: Option[Int] = None