在 Scala 中将整数列表转换为 SortedSet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6674156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:12:10  来源:igfitidea点击:

Convert List of Ints to a SortedSet in Scala

scalasortedset

提问by Andy

If I have a List of Ints like:

如果我有一个整数列表,例如:

val myList = List(3,2,1,9)

val myList = List(3,2,1,9)

what is the right/preferred way to create a SortedSet from a List or Seq of Ints, where the items are sorted from least to greatest?

从 Int 的 List 或 Seq 创建 SortedSet 的正确/首选方法是什么,其中项目从最小到最大排序?

If you held a gun to my head I would have said:

如果你拿枪指着我的头,我会说:

val itsSorted = collection.SortedSet(myList)

val itsSorted = collection.SortedSet(myList)

but I get an error regarding that there is no implicit ordering defined for List[Int].

但是我收到一个错误,提示没有为 List[Int] 定义隐式排序。

回答by huynhjl

Use:

利用:

collection.SortedSet(myList: _*)

The way you used it, the compiler thinks you want to create a SortedSet[List[Int]]not a SortedSet[Int]. That's why it complains about no implicit Ordering for List[Int].

你使用它的方式,编译器认为你想创建一个SortedSet[List[Int]]not a SortedSet[Int]。这就是为什么它抱怨没有隐式 Ordering for List[Int]

Notice the repeated parameter of type A*in the signature of the method:

注意A*方法签名中重复的 type 参数:

def apply [A] (elems: A*)(implicit ord: Ordering[A]): SortedSet[A]

To treat myListas a sequence argument of Ause, the _*type annotation.

为了治疗myList作为序列参数A使用,该_*类型的注释。

回答by Ben Challenor

You could also take advantage of the CanBuildFrominstance, and do this:

您还可以利用该CanBuildFrom实例,并执行以下操作:

val myList = List(3,2,1,9)
myList.to[SortedSet]
// scala.collection.immutable.SortedSet[Int] = TreeSet(1, 2, 3, 9)

回答by Mechanical snail

There doesn't seem to be a constructor that directly accepts List(correct me if I'm wrong). But you can easily write

似乎没有直接接受的构造函数List(如果我错了,请纠正我)。但是你可以很容易地写

val myList = List(3,2,1,9)
val itsSorted = collection.SortedSet.empty[Int] ++ myList

to the same effect. (See http://www.scala-lang.org/docu/files/collections-api/collections_20.html.)

达到同样的效果。(参见http://www.scala-lang.org/docu/files/collections-api/collections_20.html。)

回答by Landei

This is especially useful if you have to map anyway:

如果您无论如何都必须映射,这将特别有用:

import scala.collection.breakOut

val s: collection.SortedSet[Int] = List(1,2,3,4).map(identity)(breakOut)
//--> s: scala.collection.SortedSet[Int] = TreeSet(1, 2, 3, 4)