• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting in Java

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. I have a Collection of 'JT' objects. JT has date, description, amount as its properties.
2. I want to sort this collection based on a key specified by the user (date, desc, amt). What is the best way to do this in Java?
3. Additionally, the sorting could either be ascending or descending, based on what the previous sorting was. e.g. if the previous sort was date ascending, the current sort has to be date descending.
I want to use the Comparator, but don't know how (or if) to use it.
Thanks in advance!
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Welcome to JavaRanch!
Yes, you should use Comparator. In a nutshell, use Collections.sort() method, and pass as arguments two things: one, your Collection (it has to be a List) and two, an instance of a class that implements Comparator. It will look something like

To reverse the order of the sort, reverse the sign of the return value. To sort on other fields, implement other classes that compare those other fields. Easy!
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out the Java Tutorial: Collections
 
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Although it works for Arrays (Object[][]) the following class in the FormattedDataSet API may be of interest

For the javadocs: http://www.fdsapi.com/javadocs/com/fdsapi/ResultSetUtils.html
Go to http://www.fdsapi.com to download and read more about the API. It's primary use is to generate dynamic text such as xml and html.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic