更改List中元素的位置

时间:2014-09-23 06:33:02

标签: java list scala collections scala-collections

List

中有一个scala
var list=List("scala","finagle","anorm","akka","actor","play","jdbc")

如果它包含"akka"之类的元素,那么我想将其移动到第一个位置。

List("akka","scala","finagle","anorm","actor","play","jdbc")

3 个答案:

答案 0 :(得分:5)

试试这个(注意,我在输入字符串的末尾附近添加了一个额外的“akka”副本,以显示它如何收集所有匹配的字符串):

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)

答案 1 :(得分:2)

如果只有一个" akka"至多:

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)

答案 2 :(得分:2)

这是最短的(虽然在较大的列表上效率不高)解决方案:

 var list=List("scala","finagle","anorm","akka","actor","play","jdbc")
 println(list.sortBy(_ != "akka"))  // List(akka, scala, finagle, anorm, actor, play, jdbc)