tags:

views:

4475

answers:

3

I have a Map in java that has strings for both .

Data is like following <"question1", "1">, <"question9", "1">, <"question2", "4">, <"question5", "2">

I want to sort the map based on its Key's. So In the end I will have question1, question2, question3....an so on.

Eventually I am trying to get two strings out of this Map. First String: Questions ( in order 1 ..10) and Second String: Answers (in same order as question).

Right now I have the following:

Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
 questionAnswers += pairs.getKey()+",";
}

This gets me the questions in a string but they are not in order...

+17  A: 

Use a TreeMap. This is precisely what its for. If this map is passed to you and you cannot determine the type, then you can do the following:

TreeSet<String> keys = new TreeSet<String>(map.keySet());
for (String key : keys) { 
   String value = map.get(key);
   // do something
}

This will iterate across the map in natural order of the keys.

Jherico
beat me to it :P
That's OK. I'm sure once I get fired for doing nothing but refreshing SO all day I'll be too busy looking for a job to steal easy questions.
Jherico
+3  A: 

Use a TreeMap

AgileJon
+1 - Not agile enough to beat Jherico, Jon, but still pretty good. 8)
duffymo
+3  A: 

Assuming TreeMap is not good for you (and assuming you can't use generics):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.
TrayMan