0

Possible Duplicate:
Can I sort two lists in relation to each other?

I have a Sorting Scenario, I didnt know how to acheive it? Two Collections

List<<String>String> Key, List<<String>String> Value I have to sort the value from a-z and such that the key for the corresponding value should not be change.

>>eg: Key and Value  
    2=>two  
    100=>four  
    1=>five  
    0=>nine  
    3=>eight  
    8=>one

>>after Sorting:
    3=>eight  
    1=>five  
    100=>four  
    0=>nine
    8=>one
    2=>two

Any one please Help me?

Community
  • 1
  • 1
  • and after sorting is not sorted alphabetically... 8=>one, 0=>nine ? – jelies Aug 27 '12 at 07:07
  • my Lists are Separate. not in a single collection. i.e Key and value or in separate collection matched with respect to index. i have to sort the values so that key also to be re ordered. – Prabhu Prabhakaran Aug 27 '12 at 12:30

3 Answers3

1

Using a treemap with text as key ("two", "four"), we can order alphabetically and later retrieve the two lists again:

// Key contains ("2", "100", "1", ...)
// Value contains ("two", "four", "five", ...)
SortedMap<String, String> result = new TreeMap<String, String>();

// assuming the same size for both lists
for (int i = 0; i < Key.size(); i++) {
    // when adding to TreeMap, keys are ordered automatically
    result.put(Value.get(i), Key.get(i));
}

List<String> orderedKey = new ArrayList<String>(result.keySet());
List<String> orderedValue = new ArrayList<String>(result.values());

Hope this helps.

jelies
  • 9,110
  • 5
  • 50
  • 65
0

What about using a TreeMap? You have tuples of two corresponding entries and you are able to sort them as you wish.

Florian
  • 388
  • 2
  • 3
  • 13
0

Please check the information @ http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/

Amy A
  • 131
  • 4