oder keys based on the hashmap value
I have an HashMap that map String (represting Id) to Integer numbers, as result of a particular operation.
I want simply to order the entries (represented by the Sting id) based on the hashmap value.
However if I get the values set with ".values()" I will loose the coupling back to the String objects. so calling sort() will not be useful.
In practice I would like to have as output an List of the same object ordered by the map value.
[461 byte] By [
xxx-uffa] at [2007-9-30 19:52:03]

import java.util.*;
class Test130 {
public static void main(String[] args) {
Map m = new HashMap();
m.put ("Gosling", new Integer(1000));
m.put ("Joy", new Integer(2000));
m.put ("Schwartz", new Integer(3000));
m.put ("Bracha", new Integer(4000));
m.put ("Gafter", new Integer(5000));
System.out.println (" Print the hashmap as is ");
System.out.println (m);
SortedMap sm = new TreeMap (m);
System.out.println (" Print the map in sorted order ");
System.out.println (sm);
}
}
The output:
C>java -cp . Test130
Print the hashmap as is
{Bracha=4000, Gosling=1000, Joy=2000, Gafter=5000, Schwartz=3000}
Print the map in sorted order
{Bracha=4000, Gafter=5000, Gosling=1000, Joy=2000, Schwartz=3000}
import java.util.*;
class Test130 {
public static void main(String[] args) {
Map m = new HashMap();
m.put ("Gosling", new Integer(1000));
m.put ("Joy", new Integer(2000));
m.put ("Schwartz", new Integer(3000));
m.put ("Bracha", new Integer(4000));
m.put ("Gafter", new Integer(5000));
System.out.println (" Print the hashmap as is ");
System.out.println (m);
SortedMap sm = new TreeMap ();
for (Iterator it = m.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry) it.next();
sm.put (entry.getValue(), entry.getKey());
}
System.out.println (" Print the map in sorted order ");
System.out.println (sm);
}
}
Print the hashmap as is
{Bracha=4000, Gosling=1000, Joy=2000, Gafter=5000, Schwartz=3000}
Print the map in sorted order
{1000=Gosling, 2000=Joy, 3000=Schwartz, 4000=Bracha, 5000=Gafter}
Obviously if two entries have the same value you're required to change the code a little bit.
> SortedMap sm = new TreeMap ();
> for (Iterator it = m.entrySet().iterator();
> it.hasNext(); ) {
> Map.Entry entry = (Map.Entry) it.next();
> sm.put (entry.getValue(), entry.getKey());
> }
Is there a reason you aren't using:
SortedMap = new TreeMap(m);
?