Abhishek Singh
Abhishek Singh

Reputation: 61

Sort list of String based on it's value in given map

I have one String list

val str = List("A","B","C","D")

and given:

val map = Map(("A"->3),("B"->1),("C"->10),("D"->5))

To sort str list based on given map value, I have tried str.sortBy(map). It's giving me error "A" key is not found. Could someone please help me out what am I doing wrong?

Upvotes: 0

Views: 90

Answers (1)

Tomer Shetah
Tomer Shetah

Reputation: 8539

It should work as it is. Let's explain why. The signature of sortBy is:

def sortBy[B](f: A => B)(implicit ord: Ordering[B]): C = sorted(ord on f)

Therefore when you do str.sortBy(map), sortBy expects to get String => Int. str.sortBy(map) is equivalent to:

str.sortBy(s => map(s))

Note that Map extends MapOps(in Scala 2.13, in Scala 2.12 it is MapLike). MapOps(and MapLike) exposes an apply method, which takes (in your case) String and returns Int:

def apply(key: K): V = get(key) match {
  case None => default(key)
  case Some(value) => value
}

Hence writing str.sortBy(map) is the same as:

str.sortBy(s => map.apply(s))

which is the same as:

str.sortBy(map.apply)

Code run at Scastie.

Upvotes: 2

Related Questions