5

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)

2 Answers 2

12

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)
Sign up to request clarification or add additional context in comments.

2 Comments

to get the ouput from the above you add a map function val output:Array[String] = words.sortBy(w => w.length -> w.toLowerCase) map {x => x + ":" + x.length }
+1, you learn something everyday. After looking it up in the docs, it works because the Ordering object provides lexicographic ordering for tuples (see implicits Ordering.Tuple*)
-2

U can do that in one line:

 "I am a girl".toLowerCase.split(" ").map(x => (x,x.length)).sortWith { (x: (String,Int), y: (String,Int)) => x._1 < y._1 }

or in two lines:

 val wordPairs = "I am a girl".split(" ").map(x => (x,x.length))
 val result = wordPairs.toLowerCase.sortWith { (x: (String,Int), y: (String,Int)) => x._1 < y._1 }

1 Comment

You are only sorting by length, not by length + alphabetic order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.