This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Hi, Could anyone please give me some ideas on how to sort multiple columns with Collections? - let's say I have an object with 3 fields in an ArrayList; field1, field2 and field3. This can be done easily in SQL using ORDER BY field1, field2, field3 but I don't want to make use of any databases. The sort() method seemed to support only 1 column sorting and I'm not sure how we can use it to achieve multiple columns instead.
hi David what i understand from James questions is "we want to sort data for three columns". Comparator interface and sort() works for a set of objects thats it and that set of objects is one column for us. it will not be same as ORDer by field1,field2,field3. do you see what i mean here? i guess, we have say three Object here. e.g. Object field1; Object field2; Object field3; and we want the same functionality like Order by field1,field2,field3 of database. using Comparator and sort() we can do sort on any of these individually but not on (field1,field2,field3). am i making sense? let me think about how to do this. thanks! maulin
I don't know anything about Database programming so I'm not sure what it is that you are trying to acomplish but it seems like you are tyring to accomplish something like the following. Lets say you have this list: LastName FirstName SSN Adams John 123456789 Brown Mike 456123789 Brown Chris 789456132 Sort by LastName, if LastName is equal then sort by FirstName if FirstName is also equal then sort by SSN. Is this what you are trying to accomplish? Or is it something different? If it is then this isn't really that complicated and you can use Collections.sort(List,Comparator).
hi david, i agree we can use Comparator and sort() for achieving this but we need to have compare() method having the appropriate algorithm. here is the example i tried,
input file "orderby.txt" is as follows, --------------------- vasavada , Maulin , H vasavada , Niragi , H Vasavada , Niragi , H Mehta , Soham , R Mehta , Soham , J --------------------- output is, --------------------- Data before sorting vasavada,Maulin,H vasavada,Niragi,H Vasavada,Niragi,H Mehta,Soham,R Mehta,Soham,J *************************************** Data after sorting Mehta,Soham,J Mehta,Soham,R Vasavada,Niragi,H vasavada,Maulin,H vasavada,Niragi,H
Hope this helps. maulin ---------------------
Joined: Aug 09, 2002
Hi, Thanks Maulin. That's exactly what I'm trying to do. Your code works pretty well! I'll spent some time to digest the logic for it.