• 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 the best way

 
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you looked at the List and Comparator interfaces ?
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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


 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic