Search code examples
scalasortedmap

Finding the index of a specific SortedMap


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).


Solution

  • 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)