• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting the best way

 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Colin Kenworthy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you looked at the List and Comparator interfaces ?
 
Reuben Cleetus
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic