Efficiently returning the next larger value of a non-existing key in scala's sorted collections?
In scala, given a sorted map, tree or list, what is the most efficient way to return the next larger value of a non-existing key? Additionally, is it possible to get an "iterator/cursor" starting at this element?
Edit:
I'm happy with a开发者_如何学Cny interpretation of "efficiently", e.g. "runtime", "memory usage", "clarity" or "taking the smallest possible amount of programmer time to implement and maintain" (thanks Kevin Wright).
If you use a SortedMap
, then you can call range
on it. Well, sort of. It is broken up to 2.8.1 if you plan to add and/or remove elements from the map afterwards. It should be ok if you avoid these operations, and it has been fixed for upcoming Scala versions as well.
Defining "efficiently" as "taking the smallest possible amount of programmer time to implement and maintain"...
For a Sequence:
val s = Seq(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41)
val overSixteen = s dropWhile (_ < 16)
For a Map:
val s = Map(2->"a", 3->"b", 5->"c", 7->"d", 11->"e", 13->"f")
val overSix = s dropWhile (_._1 < 6)
If you prefer an Iterator, just call .iterator
on the resulting collection, or you can use .view
before dropWhile
if you're especially interested in lazy behaviour.
精彩评论