我想知道为什么Scala Set上没有sortBy方法,因为它有Seq或List因为它也扩展了Iterable ...
I'm wondering why there is no sortBy method on Scala Set as there is for Seq or List since it extends Iterable as well...
最满意答案
Set是有点有序的(这就是为什么它是Iterable)但是没有排序的元素集合。 如果要对元素进行排序,则必须使用SortedSet实现( TreeSet ),您可以在创建新实例时提供排序
更新:有序和排序之间的区别并不是很清楚:你可以说List是有序但可能没有排序,Map是无序和未排序的,但是Map的实现需要将其元素保存在内存中(RAM,磁盘) ,无论您需要什么样的支持)并且内存始终是有序的,因此它为任何集合提供了一些订单(例如,插入订单或存储顺序)。
可以在Scala API中看到这种未定义的示例:定义SortedSet时,构造函数是:
new TreeSet()(implicit ordering: Ordering[A])因此使用“排序”一词而不是“排序”
A Set is a somewhat ordered (that's why it is Iterable) but not-sorted collection of elements. If you want the elements to be sorted, you must use a SortedSet implementation (TreeSet), where you can provide the ordering when creating a new instance
Update: The difference between ordered and sorted is not really clear: You can say a List is ordered but may be not sorted and a Map is unordered and unsorted, but the implementation of a Map requires to keep its elements in memory (RAM, disk, whatever support you want) and that memory is always ordered, so it gives some order to any Collection (for example the insertion order or the storage order).
An example of this undefinition can be seen in the Scala API: When defining a SortedSet, the constructor is:
new TreeSet()(implicit ordering: Ordering[A])So the word "ordering" is used instead of "sorting"
更多推荐
发布评论