is there a more straightforward way to sort?

Basicaly in the code below the HashMap is populated and then the key and values are extracted separately. The keySet() and values() methods return a Set and a Collection respectively. The question is: Is there a faster (perhaps smarter) way to sort the keys and values separately? For the keys, I put them in a TreeSet that takes care of the sort, but for the values, I had to create an ArrayList out of the Collection and then sort it. Assuming that the instance methods of the NumberNames class are not to be altered/changed, is there perhaps a more efficient/faster way to do the sorting within the main class? I need to separately extract and sort the keys/values. Thanks for suggestions.

import java.util.*;

publicclass NumberNames{

private HashMap<String,Integer> map =new HashMap<String,Integer>();

publicvoid put(String name,int value){

map.put(name, value);

}

public Set<String> getNames(){

return map.keySet();

}

public Collection<Integer> getValues(){

return map.values();

}

publicstaticvoid main(String[] args){

NumberNames nn =new NumberNames();

nn.put("a", 1);

nn.put("b", 2);

nn.put("f", 6);

nn.put("c", 3);

nn.put("d", 4);

nn.put("e", 5);

Set s = nn.getNames();

TreeSet tr =new TreeSet(s);

Collection<Integer> val = nn.getValues();

ArrayList arl =new ArrayList(val);

Collections.sort(arl);

System.out.println(s);

System.out.println(tr);

System.out.println(val);

System.out.println(arl);

}

}

[2661 byte] By [DeChristoa] at [2007-11-26 18:29:22]
# 1

What you want to accomplish here using a TreeMap is not possible.

TreeMap can only sort based on the key. And if you really want to sort based on the value as well( which, of course, is not possible with a TreeMap), it may mess up with the order of the keys.

So sorting both at the same time does not make any sense.

FUN_ONEa at 2007-7-9 6:03:31 > top of Java-index,Java Essentials,New To Java...
# 2

> For the keys, I put them in a

> TreeSet that takes care of the sort, but for the

> values, I had to create an ArrayList out of the

> Collection and then sort it.

Maybe I missed something why did you do this with the values? Why couldn't you use a TreeSet just like for the keys?

Also, if you are sorting them separately why are they ever in this map?

zadoka at 2007-7-9 6:03:31 > top of Java-index,Java Essentials,New To Java...
# 3
Well, yes. Actually you are right , a TreeSet for the values would have saved me all these extra lines. Thanks.... I guess my question was more confusing that it should've been. But I see what you mean.
DeChristoa at 2007-7-9 6:03:31 > top of Java-index,Java Essentials,New To Java...