aspose file tools*
The moose likes Java in General and the fly likes Sorting the best way Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting the best way" Watch "Sorting the best way" New topic
Author

Sorting the best way

Dale DeMott
Ranch Hand

Joined: Nov 02, 2000
Posts: 515
I'm looking for a good way to sort a list of elements. I want to be able to sort by a primary key and then a secondary key. Example: I have a dataset with the following elements
Last Name First Name Phone
Jones Jack 555-1234
Jones Abe 555-3234
Smith Jack 555-5334
Jones Rick 555-5124
I want to be able to sort by Last Name and if any match in the last name, I want to then sort by first name...
How should I approach this??
-Dale

------------------
By failing to prepare, you are preparing to fail.
Benjamin Franklin (1706 - 1790)


By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
Colin Kenworthy
Ranch Hand

Joined: Aug 06, 2001
Posts: 88
Have you looked at the List and Comparator interfaces ?
Reuben Cleetus
Ranch Hand

Joined: Jul 13, 2001
Posts: 50
As one of the people who replied said, the Comparator interface is what you're looking for. It lets you define how to compare two objects, so that when you call a sort on an array of those objects, the sort algorithm knows how the objects can be compared to each other.
This is probably the 'easy way' for you. However, you may find that the sorting algorithm is not the most efficient, or perhaps you want a sort mechanism of your own. In that case, you can find resources on the web (Just seach for 'sort and java' on google), to design a better sort algorithm, while still using the Comparator interface to compare two objects.
Regards,
Reuben.

Originally posted by Dale DeMott:
I'm looking for a good way to sort a list of elements. I want to be able to sort by a primary key and then a secondary key. Example: I have a dataset with the following elements
Last Name First Name Phone
Jones Jack 555-1234
Jones Abe 555-3234
Smith Jack 555-5334
Jones Rick 555-5124
I want to be able to sort by Last Name and if any match in the last name, I want to then sort by first name...
How should I approach this??
-Dale


 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting the best way