I wish to sort a list containing (word, word.length) first based on length and then words alphabetically. So given: "I am a girl"
the output should be a:1, I:1, am:2, girl:4
I have the following piece of code which works but not for all examples
val lengths = words.map(x => x.length)
val wordPairs = words.zip(lengths).toList
val mapwords = wordPairs.sort (_._2 < _._2).sortBy(_._1)
You can sort by tuple:
scala> val words = "I am a girl".split(" ")
words: Array[java.lang.String] = Array(I, am, a, girl)
scala> words.sortBy(w => w.length -> w)
res0: Array[java.lang.String] = Array(I, a, am, girl)
scala> words.sortBy(w => w.length -> w.toLowerCase)
res1: Array[java.lang.String] = Array(a, I, am, girl)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With