我需要一个示例,说明如何在 HashSet
上使用可比较的类来获得升序。假设我有一个像这样的 HashSet
:
HashSet<String> hs = new HashSet<String>();
如何让 hs
按升序排列?
最佳答案
使用 TreeSet
反而。它有一个 constructor taking a Comparator
.它会自动对Set
进行排序。
如果要将 HashSet
转换为 TreeSet
,请执行以下操作:
Set<YourObject> hashSet = getItSomehow();
Set<YourObject> treeSet = new TreeSet<YourObject>(new YourComparator());
treeSet.addAll(hashSet);
// Now it's sorted based on the logic as implemented in YourComparator.
如果您拥有的项目本身已经实现 Comparable
并且它的默认排序顺序已经是你想要的了,那么你基本上不需要提供Comparator
。然后,您可以直接基于 HashSet
构造 TreeSet
。例如
Set<String> hashSet = getItSomehow();
Set<String> treeSet = new TreeSet<String>(hashSet);
// Now it's sorted based on the logic as implemented in String#compareTo().
另见:
关于java - 订购哈希集示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380312/