我有一个可变的 SortedSet,我可以通过执行 for (item <- nameOfMySortedSet)
来迭代它。不过,我希望能够做同样的事情,但与nameOfMySortedSet
相反。 。我似乎没有看到reverse()
该数据类型的选项?还有其他方法可以做到这一点吗?
最佳答案
您可以尝试构建一个新的 SortedSet,并颠倒顺序:
scala> val mySet = collection.mutable.SortedSet("1", "2", "3")
mySet: scala.collection.mutable.SortedSet[String] = TreeSet(1, 2, 3)
scala> collection.mutable.SortedSet(mySet.toSeq:_*)(mySet.ordering.reverse)
res0: scala.collection.mutable.SortedSet[String] = TreeSet(3, 2, 1)
或者您可以将其转换为列表或序列并运行相反的操作:
scala> mySet.toSeq.reverse
res1: Seq[String] = ArrayBuffer(3, 2, 1)
关于scala - 迭代 Scala 中排序集的逆序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30736869/