按相反顺序对Set进行排序 [英] Sort a Set in reverse order
问题描述
为新手问题道歉,但是反向获取 Set
(比如 LinkedHashSet
)的正确方法是什么订购?对于 Collection
s, Collections.reverse(Collection c)
,但如何为<$ c $做一个c>使用有序元素设置(如 LinkedHashSet
)?
Apologies for the newbie question, but what's the proper way to get a Set
(say LinkedHashSet
) in reverse order? For Collection
s there's Collections.reverse(Collection c)
, but how does one do it for a Set
with ordered elements (like a LinkedHashSet
)?
推荐答案
一般不对集合进行排序,因此为了保留排序,在将集合排序为列表之后,您需要使用Set的已知迭代顺序实现,例如LinkedHashSet
Sets are not ordered in general, so to preserve the sorting, after sorting the set as a list, you would need to use a known iteration order implementation of Set, such as LinkedHashSet
List list = new ArrayList(set);
Collections.sort(list, Collections.reverseOrder());
Set resultSet = new LinkedHashSet(list);
您也可以将TreeSet与比较器一起使用,但这并不像上面的ArrayList方法那么快。
You could also use TreeSet with a comparator, but that is not as fast as the ArrayList method above.
这篇关于按相反顺序对Set进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!