我正在尝试通过获取字符串并对字符串中的数字进行排序来对mutable.Map [String,String]进行排序。输入:
"Liz", "Game: 2"
"Philip", "Game: 5"
"Philip", "Game: 0"
输出到这样的东西
"John", "Game: 5"
"Liz", "Game: 2"
"Philip", "Game: 0"
我已经尝试过此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)
创建案例类:
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))