如何从 Set 和 Comparator 中获取 List
从 Set
获取 List
并根据给定的 Comparator
进行排序的“好”(以及为什么?)解决方案是什么?
What is the "good" (and why ?) solution to get a List
from a Set
and sorted against a given Comparator
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需构建它即可。
ArrayList
有一个 构造函数采用另一个集合
。Just construct it. The
ArrayList
has a constructor taking anotherCollection
.要么:
要么:
Either:
or:
假设您从未排序的集合或按不同顺序排序的集合开始,以下可能是最有效的假设您需要可修改的列表。
如果不可修改的列表是可接受的,那么以下方法会更快一些:
在第一个版本中,
Collections.sort(...)
将列表内容复制到数组中,对数组进行排序,然后复制已排序的元素返回到列表。第二个版本更快,因为它不需要复制已排序的元素。但说实话,性能差异可能并不显着。事实上,随着输入集大小变大,性能将主要由进行排序的 O(NlogN) 时间决定。复制步骤的复杂度为
O(N)
,并且随着 N 的增长,其重要性也会降低。Assuming that you start with an unsorted set or a set sorted on a different order, the following is probably the most efficient assuming that you require a modifiable List.
If an unmodifiable List is acceptable, then the following is a bit faster:
In the first version,
Collections.sort(...)
copies the list contents to an array, sorts the array, and copies the sorted elements back to the list. The second version is faster because it doesn't need to copy the sorted elements.But to be honest the performance difference is probably not significant. Indeed, as the input set sizes get larger, the performance will be dominated by the
O(NlogN)
time to do the sorting. The copying steps areO(N)
and will reduce in importance as N grows.这就是当您拥有
Set
时获取List
的方式:不确定您希望使用
Comparator
做什么。如果Set
已排序,则列表将包含按排序顺序的元素。This is how you get a
List
when you have aSet
:Not sure what you expect to do with the
Comparator
. If theSet
is sorted, the list will contain the elements in sorted order.