[英]Change the position of element in List
There is a List
in scala
在
scala
有一个List
var list=List("scala","finagle","anorm","akka","actor","play","jdbc")
If it is containing an element like "akka"
then i want to move it to the 1st position. 如果它包含
"akka"
类的元素,那么我想将其移至第一位置。
List("akka","scala","finagle","anorm","actor","play","jdbc")
Try this (note, I added an extra copy of "akka" near the end of the input string to show how it collects all matching strings): 试试这个(注意,我在输入字符串的末尾添加了一个额外的“ 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)
If there's only one "akka" at most: 如果最多只有一个“ 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)
Here is shortest (though not very efficient on larger lists) solution: 这是最短的解决方案(尽管在较大的列表中效率不高):
var list=List("scala","finagle","anorm","akka","actor","play","jdbc")
println(list.sortBy(_ != "akka")) // List(akka, scala, finagle, anorm, actor, play, jdbc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.