• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sorting the list based on another list

 
Nareshkumar Kapilavai
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 272
C++ Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic