Return A Sorted Collection Of Items

From CodeCodex

Revision as of 10:08, 11 August 2012 by Ldo (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Java

If you have an array of items, it is easy enough to sort them using one of the sort methods in java.util.Arrays. However, suppose they are being returned from an iterator; instead of collecting them into, say, into an ArrayList, extracting an array from that, and doing the sort, you can use a TreeSet to collect the elements in a single process, from which they are immediately ready to be read out in the right order.

Suppose the items you want to sort are of the time MyItemType. First define a suitable specialization of TreeSet with a custom Comparator that defines the order you want:

   java.util.TreeSet<MyItemType> SortedItems = new java.util.TreeSet<MyItemType>
     (
       new java.util.Comparator<MyItemType>()
         {
           public int compare
             (
               MyItemType Item1,
               MyItemType Item2
             )
             {
               return
                   ...value defining order..;
             } /*compare*/
         } /*Comparator*/
     );

Then, collect the items from wherever and insert them into SortedItems, in any order, e.g.:

   for (MyItemType ThisItem : ... unsorted iterator ...)
     {
       SortedItems.add(ThisItem);
     } /*for*/

Once you have inserted all the items, you can read them back out again in sorted order:

   for (MyItemType ThisItem : SortedItems)
     {
       ... process in sorted order ...
     } /*for*/

Because a TreeSet implements Iterable, you can also return it directly from a method that is supposed to produce some sorted list of items, e.g.

   public iterable<MyItemType> ForSortedItems
     (
       ... source of unsorted items, database query etc ...
     )
     {
       ... declare and fill in SortedItems as above...
       return
           SortedItems;
     } /*ForSortedItems*/

which can then be used as

   for (MyItemType ThisItem : ForSortedItems(... source of unsorted items, database query etc ...))
     {
       ...
     } /*for*/