Scala 如何对具有字符串的地图进行排序,其中包含数字

Scala How do you sort a map that has a String, with numbers in it

我正在尝试通过获取字符串并使用字符串中的数字排序来对 mutable.Map[String, String] 进行排序。 输入:

"Liz", "Game: 2"
"Philip", "Game: 5"
"John", "Game: 0 | Score: 9"
"Kevin", "Game: None"

输出成这样

"John", "Game: 5 | Score: 9"
"Liz", "Game: 2"
"Philip", "Game: 0"
"Kevin", "Game: None"

我试过了https://alvinalexander.com/scala/how-to-sort-map-in-scala-key-value-sortby-sortwith/ 但它并没有按照我想要的方式进行排序 请原谅我的语法错误

您需要从字符串中获取数字并将其转换为 Integer,例如:

val map: Map[String, String] = Map(("Liz", "Game: 11"), ("Philip", "Game: 5"))
val order: ((String, String)) => Integer = { case (_ , p2) => p2.stripPrefix("Game: ").toInt }
map.toSeq
  .sortWith(order(_) > order(_))
  .toList

示例数据:

scala> tmp
res19: scala.collection.mutable.Map[String,String] = Map(Philip -> Game: 0, John -> Game: 5, Liz -> Game: 2)

创建案例class:

case class someclass(name:String,score:Int,keyword:String)

将数据放入List[someClass]:

val listOfScores = tmp.map(each => { 
  val name = each._1
  val keyword = each._2.split(":")(0)
  val score = each._2.split(":")(1).stripPrefix(" ").toInt
  someclass(name,score,keyword)
})

最后排序得到最终列表:

scala> listOfScores.toList.sortBy(_.score).reverse
res31: List[someclass] = List(someclass(A1,9,Goals), someclass(a2,5,Game), someclass(Liz,2,Game), someclass(John,0,Score), someclass(Philip,0,Game))

Scala 标准库知道如何对相同类型配置文件的元组进行排序,只要所有内部元素都可以排序即可。

只要option元素可以排序,它也知道怎么排序。

Float 个值可以排序。

因此,您可以按内部 IntFloat 值对 String 进行排序,这些值可能存在,也可能不存在,方法是将它们填充到 Option[Float] 的元组中元素。

import scala.util.Try

val games =
  scala.collection.mutable.Map("Liz"  -> "Game: 2"
                              ,"John" -> "Game: 0 | Score: 9"
                              ,"Philip" -> "Game: 5"
                              ,"Kevin"  -> "Game: None")
games.put("Jo", "Game: 11 | Score 0")

val numRE = "\d*\.?\d+".r

games.toList.sortBy { case (_, str) =>
  val ns = numRE.findAllIn(str)
                .flatMap(n => Try(n.toFloat).toOption)
                .toVector
  (ns.lift(0), ns.lift(1))
}.reverse
//res1: List[(String, String)] = List((Jo,Game: 11 | Score 0)
//                                  , (Philip,Game: 5)
//                                  , (Liz,Game: 2)
//                                  , (John,Game: 0 | Score: 9)
//                                  , (Kevin,Game: None))