I think slice on TreeSet quite efficient (and you can use it with a singleton range), but you are right - it is strange that there is no indexed sorted data structure. And it is quite effective; most of any sorted tree can be used this way if the number of children is tracked. I think this is just an oversight that it is missing.
You can always use a set for repeating elements if you wrap them with a tag that allows only reference equality, and you can make sure that they are ordered:
class Tag[A](val value: A)(implicit ord: Ordering[A]) extends Ordered[Tag[A]] { def compare(ta: Tag[A]) = { val c = ord.compare(value,ta.value) if (c != 0) c else if (this eq ta) 0 else System.identityHashCode(this) compare System.identityHashCode(ta) } override def toString = value.toString+"'" override def hashCode = value.hashCode override def equals(a: Any) = a.asInstanceOf[AnyRef] eq this } scala> collection.immutable.TreeSet[Tag[Int]]() ++ List(1,2,3,2,1).map(i => new Tag(i)) res1: scala.collection.immutable.TreeSet[Tag[Int]] = TreeSet(1', 1', 2', 2', 3') scala> res1.slice(2,3).head res2: Tag[Int] = 2'
This adds a lot of overhead for a relatively simple task.
source share