• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to sort a Set  RSS feed

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to sort a Set how can I do that.

Thanks.
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer, is "you can't". A Set is not an ordered Collection.

A longer, and hopefully more useful, answer is that there are a variety of ways that you can get a sorted version of the information that is in a Set.

You could do toArray() on the Set, then Arrays.sort().

You could switch from a Set to a SortedSet such as TreeSet.

You could switch from a Set to a List like ArrayList and use Collections.sort().

There are a variety of reasons for choosing different options. For example, if you need the no-duplicates feature of a Set, then ArrayList is no good.
[ November 01, 2007: Message edited by: Peter Chase ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!