I founding an existing question that I am interested in having the answer to , however the proposed solution appears to sort by the key and not by the value. How do you go about sorting by the value?
Below is the question/solution I am referencing.
Solution Title: Sorting TreeMap by values
asked by durban_posion on 02/23/2003 08:17AM PST
This solution was worth 50 Points and received a grade of A
Hi there,
How do I sort TreeMap by integer values?
TreeMap example:
Map map = new TreeMap(comp);
map.put("1", "1000");
map.put("6", "4000");
map.put("8", "3000");
map.put("25", "10000");
map.put("13", "5000");
map.put("19", "6000");
Result should be:
key value
1 1000
8 3000
6 4000
13 5000
19 6000
25 10000
Thanks DP
Send to a Friend Printer Friendly See Solution
Comment from CEHJ
Date: 02/23/2003 08:19AM PST
Comment
It's already sorted by that value
Comment from durban_posion
Date: 02/23/2003 08:32AM PST
Author Comment
It is not
if u iterate this map result will be sorted by keys, not values.
1 1000
6 4000
8 3000
13 5000
19 6000
25 10000
What I need is something that sotrs this map by values (1000,3000,4000, etc)
But thanks anyway for quick respond
Comment from CEHJ
Date: 02/23/2003 08:50AM PST
Comment
Oh, i thought you meant by the integer key.
TreeSet ts = new TreeSet(new ValSorter());
ts.addAll(map.values());
..............
class ValSorter implements Comparator {
public int compare(Object o1, Object o2) {
return new Integer((String)o1).compar
eTo(new Integer((String)o2));
}
}
Comment from CEHJ
Date: 02/23/2003 08:51AM PST
Comment
You can print the set by:
System.out.println(ts);
Comment from durban_posion
Date: 02/23/2003 09:07AM PST
Author Comment
I also need keys.
Map must be sorted by values but must contain a key/value pair not just value as in your example.
Result should be:
key value
1 1000
8 3000
6 4000
13 5000
19 6000
25 10000
Thanks
Accepted Answer from CEHJ
Date: 02/23/2003 09:18AM PST
Grade: A
Accepted Answer
You have two alternatives - don't use Strings as keys as you've done or create the map using the class i gave you:
Map map = new java.util.TreeMap(new ValSorter());
Comment from CleanupPing
Date: 08/03/2003 03:00AM PDT
Comment
durban_posion:
This old question needs to be finalized -- accept an answer, split points, or get a refund. For information on your options, please click here->
http:/help/closing.jsp#1 EXPERTS:
Post your closing recommendations! No comment means you don't care.
Administrative Comment from AnnieMod
Date: 11/12/2003 04:00AM PST
Administrative Comment
Force accepted
AnnieMod
Community Support Moderator @ Experts-Exchange