Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 4381

Sorting TreeMap by values

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

0
durban_posion
1 Solution

Commented:
It's already sorted by that value
0

Author Commented:
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
0

Commented:
Oh, i thought you meant by the integer key.

TreeSet ts = new TreeSet(new ValSorter());

..............

class ValSorter implements Comparator {
public int compare(Object o1, Object o2) {
return new Integer((String)o1).compareTo(new Integer((String)o2));
}
}
0

Commented:
You can print the set by:

System.out.println(ts);
0

Author Commented:
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
0

Commented:
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());
0

Commented:
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.
0

Commented:
I am interested in the solution to this problems as well, however the propsoed solution appears to sort by the key and not by the value.  How do you go about sorting by the value?
0

Featured Post

Tackle projects and never again get stuck behind a technical roadblock.