This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have an application that pulls some data from a relational database table and writes it out to a web page (using java beans/jsp pages). Currently my code pulls the data from the relational database table into a java List like this:
Now I'm in the position where I need to do the above more than once to pull data from different tables together. I can append one list to the other, but now I'm not sure how I can sort it.
An example of my list would be: 0 Alan 1 Smith 2 Red 3 09/09/2007 4 Ann 5 Jones 6 Yellow 7 10/11/2005 8 Fred 9 Williams 10 Blue 11 06/02/2008 ...
I now need to sort it by date, keeping the sets of 4 together (Alan Smith Red 9/9/2007 needs to stay together).
When I populate my list, I could populate as such: 0 09/09/2007~Alan~Smith~Red 1 10/11/2005~Ann~Jones~Yellow 2 06/02/2008~Fred~Williams~Blue ... and then sort it then split out the string to write it to web page. I'm not sure how well that would work, but it seems like there must be a better way.
Being new to java I don't really know what my options are. It seems like there must be a better way. Is there some other way I should be doing this? Should I be putting my data into an array? A map? Something else I don't know about yet (which is a lot!)
Your best bet would be to create an object that contains the four properties that are shared. Put all the instances of this object into a list, and generate a Comparator that orders the list as you need them.
You could then have a Comparator that compares one Person with another based on whatever criterion you define, and orders them appropriately. See This On Java Article for some help with that.
Joined: Apr 11, 2008
Thank you so much! This really helps! I'm off to give it a try!