One option would be to define a custom ordering for a TreeMap. TreeMap is a sorted implementation of Map
import scala.collection.immutable.TreeMap
implicit object LengthOrder extends Ordering[String] {
def compare(s1: String, s2: String) = s1.length - s2.length
}
val randomMap = TreeMap("111" -> "111", "1" -> "1", "11" -> "11")
//randomMap: TreeMap[String,String] = Map(1 -> 1, 11 -> 11, 111 -> 111)
val keys = randomMap.keys
//keys: Iterable[String] = Set(1, 11, 111)
Note that this will affect all TreeMap[String]s where LengthOrder is in scope. In your project you could nest LengthOrder in another object (or put it in its own package) and then only import it inside the specific code blocks that need it.
Edit:
@Bharadwaj made a good point about how this would destroy all but one keys that have the same length. Something like this would fix this issue:
implicit object LengthOrder extends Ordering[String] {
def compare(s1: String, s2: String) = s1.length - s2.length match {
case 0 => s1.compareTo(s2)
case x => x
}
}
List[Tuple2[..]](or other sequence of key-value pairs, etc) to maintain the ordering after a sort operation. Alternatively, see SortedMap if accessing by key is still important.