jshah jshah - 3 months ago 13
Scala Question

Can I call a method inside of sortWith when sorting a sequence (or a map)?

I have a map Map[String,Option[Seq[String]]] and I have values for each of the string in a different map: Map[String,Option[Int]]. I am trying to map over the values and use a sortWith on the sequence but as I read online, I don't see any examples of having custom methods inside the sortWith.

How can I sort my sequence using sortWith? If I wanted to implement a custom method that returns a boolean to tell me what object is considered greater, is this possible?

val fieldMap = Map("user1" -> Seq("field1_name", "field2_name"), "user2" -> Seq("field3_name"))
val fieldValues = Map("field1_name" -> 2, "field2_name" -> 1, "field3_name" -> 3)

val sortedMap = fieldMap.mapValues(fieldList => fieldList.sortWith(fieldValues(_) < fieldValues(_)) // Scala doesn't like this


I tried:

fieldList.sortWith{(x,y) =>
val x = fieldValues(x)
val y = fieldValues(x)

x < y
}


This gives me a Type mismatch of expected type:

(String,String) => Boolean


and actual:

(String,String) => Any


EDIT Solution:

fieldList.sortWith{(x,y) =>
val x = fieldValues(x)
val y = fieldValues(x)

x.getOrElse[Double](0.0) < y.getOrElse[Double](0.0) // have to unwrap the Option.
}

Answer

You're using wrong syntax. For using sortWith you have to do something like:

fieldMap.mapValues(
   fieldList => fieldList.sortWith(
     (a,b) => fieldValues(a) > fieldValues(b)
   )
)