Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala sort list based on second attribute and then first

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)
like image 350
princess of persia Avatar asked Jan 23 '13 06:01

princess of persia


1 Answers

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)
like image 108
Sergey Passichenko Avatar answered Oct 18 '22 12:10

Sergey Passichenko