Java 如何从集合和比较器中获取列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3923429/
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
How get List from Set and Comparator
提问by Manuel Selva
What is the "good" (and why ?) solution to get a List
from a Set
and sorted against a given Comparator
?
List
从 a获取aSet
并针对给定的排序的“好”(以及为什么?)解决方案是Comparator
什么?
采纳答案by Tyler Treat
Set<Object> set = new HashSet<Object>();
// add stuff
List<Object> list = new ArrayList<Object>(set);
Collections.sort(list, new MyComparator());
回答by BalusC
Just construct it. The ArrayList
has a constructor taking another Collection
.
构建它就行了。该ArrayList
有一个构造函数服用另一种Collection
。
Set<Foo> set = new TreeSet<Foo>(new FooComparator<Foo>());
// Fill it.
List<Foo> list = new ArrayList<Foo>(set);
// Here's your list with items in the same order as the original set.
回答by Michael Borgwardt
This is how you get a List
when you have a Set
:
List
当你有一个时,这就是你如何得到一个Set
:
List list = new ArrayList(set);
Not sure what you expect to do with the Comparator
. If the Set
is sorted, the list will contain the elements in sorted order.
不确定您希望用Comparator
. 如果Set
已排序,则列表将包含按排序顺序的元素。
回答by iirekm
Either:
任何一个:
Set<X> sortedSet = new TreeSet<X>(comparator); ...
List<X> list = new ArrayList<X>(sortedSet);
or:
或者:
Set<X> unsortedSet = new HashSet<X>(); ...
List<X> list = new ArrayList<X>(unsortedSet);
Collections.sort(list, comparator);
回答by Stephen C
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.
假设您从一个未排序的集合或一个按不同顺序排序的集合开始,假设您需要一个可修改的 List,以下可能是最有效的。
Set<T> unsortedSet = ...
List<T> list = new ArrayList<T>(unsortedSet);
Collections.sort(list, comparator);
If an unmodifiable List is acceptable, then the following is a bit faster:
如果一个不可修改的 List 是可以接受的,那么下面的速度会更快一些:
Set<T> unsortedSet = ...
T[] array = new T[unsortedSet.size()];
unsortedSet.toArray(array);
Arrays.sort(array, comparator);
List<T> list = Arrays.asList(array);
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.
在第一个版本中,Collections.sort(...)
将列表内容复制到数组中,对数组进行排序,然后将排序后的元素复制回列表。第二个版本更快,因为它不需要复制已排序的元素。
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 are O(N)
and will reduce in importance as N grows.
但老实说,性能差异可能并不显着。实际上,随着输入集大小变大,性能将取决于进行O(NlogN)
排序的时间。O(N)
随着 N 的增加,复制步骤的重要性将会降低。