按相反顺序对Set进行排序 [英] Sort a Set in reverse order

查看:505
本文介绍了按相反顺序对Set进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为新手问题道歉,但是反向获取 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 Collections 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆