List 根据索引列表对列表进行排序

List 根据索引列表对列表进行排序,list,scala,sorting,List,Scala,Sorting,假设我有一张无序的名单 val unsorted = List("third", "second", "fourth", "first") 我还有另外一个列表,上面列表的索引按正确的顺序排列 val ids = List(3, 1, 0, 2) 如何使用这些索引对未排序的进行排序以获得此结果 List("first", "second", "third", "fourth") 只需将ID映射到未排序的列表本身 scala> val sorted = ids map unsorted.

假设我有一张无序的名单

val unsorted = List("third", "second", "fourth", "first")
我还有另外一个列表,上面列表的索引按正确的顺序排列

val ids = List(3, 1, 0, 2)
如何使用这些索引对未排序的
进行排序以获得此结果

List("first", "second", "third", "fourth")

只需将ID映射到未排序的列表本身

scala> val sorted = ids map unsorted.toIndexedSeq
sorted: List[String] = List(first, second, third, fourth)

unsorted
转换为
IndexedSeq
是不必要的,但正如@gzm0在下面指出的那样,它可以防止此操作成为
O(n^2)

考虑首先在
unsorted
上调用
toIndexedSeq
,否则这将是
O(n^2)