Sorting HashMap by values, *not* key
How can I sort a HashMap by the value, it seems it is sorted always by the key.
Let's say I have the following code:
HashMap<String, Object[]> drivers =new HashMap<String, Object[]>();
try{
p = c.prepareStatement("SELECT " +
"NOME, " +
"CPF " +
"FROM MOTORISTAS " +
"ORDER BY 1;");
ResultSet rs = p.executeQuery();
while(rs.next()){
drivers.put(rs.getString("CPF"),new Object[]{rs.getString("NOME"), rs.getString("CPF")});
}
rs.close();
p.close();
}catch (SQLException e){
TG.Mess("ERROR: Selecting Drivers", e.getMessage());
drivers =null;
}
I want to sort by the first Object[]
position in the value.
I know I can use TreeMap, but it's not working as following:
TreeMap<String, Object[]> treeMap =new TreeMap<String, Object[]>(drivers);
Set set = treeMap.entrySet();
Iterator it = set.iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Object[] driver = (Object[])entry.getValue();// {NOME, CPF}
String line = driver[0]+" | "+driver[1];
System.out.println("Line: "+line);
}
[2056 byte] By [
Franziska] at [2007-11-26 18:25:44]

# 1
> How can I sort a HashMap by the value, it seems it is
> sorted always by the key.
According to the TreeMap API: "This class guarantees that the map will be in ascending key order"
If you want it sorted differently just sort it after you get the value set back..
For example you could use Collections.sort() or put it into a sorted list.
I would suggest posting questions like this in the "Java Programming" forum in the future.
# 2
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("One",6);
map.put("Two",1);
map.put("Threee",2);
map.put("Four",2);
map.put("Five",8);
map.put("Six",3);
List<Map.Entry><String, Integer>> list = new ArrayList<Map.Entry><String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry><String, Integer>>()
{
public int compare(Map.Entry<String, Integer> left, Map.Entry<String, Integer> right)
{
if (left.getValue() < right.getValue())
return -1;
else if (left.getValue() > right.getValue())
return +1;
else
return 0;
}
});
for (Map.Entry<String, Integer> entry : list)
{
System.out.println(entry.getValue() + "\t" + entry.getKey());
}