*
The moose likes Java in General and the fly likes sorting the list based on another list 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 list based on another list" Watch "sorting the list based on another list" New topic
Author

sorting the list based on another list

Nareshkumar Kapilavai
Greenhorn

Joined: May 29, 2007
Posts: 25
Hi,
i have a list of strings having some order, i need to sort the another list based on the first list.for ex. in the first list contains the values
in following order

CURR
REPO
TBD
TBL
TN
BA
CD
CP
TD
CN
AGCY
DN
MUNI
COM
CB

and my second list is like this..

DN
DN
DN
TD
TD
TD
TBD
TBD
TBD
CURR
BA
BA


i need to sort the second list values based on the first list order.. if there is any new values in the second list, which are not held in the first list shoulb be come bottom of the second list..

please suggest me the logic for this.
Thanks
Naresh
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
I suspect the easiest way to do this will be by writing a custom implementation of java.util.Comparator which can be used in a call to Collections.sort().

Bill
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Then when you initialise your Comparator, pass in the list used for ordering.

As each pair of strings are passed in for comparison, convert them into ints using originalList.indexOf, except that if the index is -1, change the index to originalList.size()

Compare the two ints. QED.
Anand Hariharan
Rancher

Joined: Aug 22, 2006
Posts: 257

Originally posted by David O'Meara:
Then when you initialise your Comparator, pass in the list used for ordering.

As each pair of strings are passed in for comparison, convert them into ints using originalList.indexOf, except that if the index is -1, change the index to originalList.size()

Compare the two ints. QED.


One tiny improvement I can think of is, when the Comparator is initialised with the original list, it could hash the strings in the original list with their indices as the value.

I suspect that the typical implementation of indexOf will have linear complexity, and so we might avoid this at every comparison.

- Anand


"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: sorting the list based on another list
 
Similar Threads
Generic Java
Reading rows based on column value in POI
insertion of data
test bed for array based list implementation
Pleas help with array