Reputation: 4101
For instance, how can I sort this Array by points and name using a function like Scala's sortWith
:
val arr = Array(
Map("name"->"A","points"->"10"),
Map("name"->"B","points"->"9"),
Map("name"->"C","points"->"8") )
Sort by points only:
arr.sortWith(_.get("points").getOrElse("0").toLong < _.get("points").getOrElse("0").toLong)`
Upvotes: 1
Views: 190
Reputation: 1078
You can use the sortBy function:
arr.sortBy( ( m: Map[String, String] ) => ( ( m.getOrElse( "points", "0" ).toLong, m.get( "name" ) ) ) )
This above snippet will sort by points first (smallest to largest), then to break any ties then alphabetically by the name (asc).
The function "comparator" passed in to the sortBy function may return a value that is a tuple (one or more discriminators to sort by). So in this case, I'm returning ( points, name )
Upvotes: 3