Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ordering a hashset example?

Tags:

I need an example on how to use a comparable class on a HashSet to get an ascending order. Let’s say I have a HashSet like this one:

HashSet<String> hs = new HashSet<String>();

How can I get hs to be in ascending order?

like image 283
Jony Avatar asked Aug 01 '10 00:08

Jony


2 Answers

Use a TreeSet instead. It has a constructor taking a Comparator. It will automatically sort the Set.

If you want to convert a HashSet to a TreeSet, then do so:

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.

If the items you have itself already implements Comparable and its default ordering order is already what you want, then you basically don't need to supply a Comparator. You could then construct the TreeSet directly based on the HashSet. E.g.

Set<String> hashSet = getItSomehow();
Set<String> treeSet = new TreeSet<String>(hashSet);
// Now it's sorted based on the logic as implemented in String#compareTo().

See also:

  • Object ordering tutorial
  • Collections tutorial - Set Implementations
like image 60
BalusC Avatar answered Oct 18 '22 23:10

BalusC


HashSet "makes no guarantees as to the iteration order of the set." Use LinkedHashSet instead.

Addendum: I would second @BalusC's point about implementing Comparable and express a slight preference for LinkedHashSet, which offers "predictable iteration order ... without incurring the increased cost associated with TreeSet."

Addendum: @Stephen raises an important point, which favors @BalusC's suggestion of TreeMap. LinkedHashSet is a more efficient alternative only if the data is (nearly) static and already sorted.

like image 38
trashgod Avatar answered Oct 19 '22 00:10

trashgod