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: 12269
1
posted
0
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().
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()
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