有一個List
在scala
更改列表
var list=List("scala","finagle","anorm","akka","actor","play","jdbc")
如果含有像"akka"
的元素的話,我想將它移動到第一的位置。
List("akka","scala","finagle","anorm","actor","play","jdbc")
有一個List
在scala
更改列表
var list=List("scala","finagle","anorm","akka","actor","play","jdbc")
如果含有像"akka"
的元素的話,我想將它移動到第一的位置。
List("akka","scala","finagle","anorm","actor","play","jdbc")
如果只有一個「阿卡」最多:
var (before, after) = list.span(_ != "akka")
//> before : List[String] = List(scala, finagle, anorm)
//| after : List[String] = List(akka, actor, play, jdbc)
if (after.isEmpty) list else "akka" :: (before ::: after.tail)
//> res0: List[String] = List(akka, scala, finagle, anorm, actor, play, jdbc)
試試這個(注意,我說的「阿卡」的額外拷貝附近的輸入字符串的結尾,以顯示它如何收集所有匹配的字符串):
scala> val inList = List("scala","finagle","anorm","akka","actor","play","akka","jdbc")
inList: List[String] = List(scala, finagle, anorm, akka, actor, play, akka, jdbc)
scala> val partitioned = inList.partition(_ == "akka") // Or whatever partition function suits your need
partitioned: (List[String], List[String]) = (List(akka, akka),List(scala, finagle, anorm, actor, play, jdbc))
scala> val outList = partitioned._1 ::: partitioned._2
outList: List[String] = List(akka, akka, scala, finagle, anorm, actor, play, jdbc)
這裏是最短的(儘管不是在大名單非常有效的)解決方案:
var list=List("scala","finagle","anorm","akka","actor","play","jdbc")
println(list.sortBy(_ != "akka")) // List(akka, scala, finagle, anorm, actor, play, jdbc)
但現在有兩個'akka' – 2014-09-23 07:31:18
這是因爲Shadowlands在原始列表中添加了兩個以清楚表明他的解決方案如何處理列表中的多個「akka」。如果原始列表中只有一個,它將按您的要求工作。 – 2014-09-23 07:33:13