• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Comparator with TreeNap

 
pradeep selvaraj
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a TreeMap as follows

TreeMap<String,Integer> mymap = new TreeMap<String,Integer>

I want mymap to be sorted according to the integer field, using Comparator. Can anyone tell me how it can be done.

Thanks

Serish
 
Campbell Ritchie
Sheriff
Pie
Posts: 49865
71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look in the API specification for TreeMap, and see which way it is sorted.
In most maps, you have a key and a value, and you use the key for inserting and finding the values.
I presume by integer, you mean Integer.
Go to the API, which we should be reading all the time.
Find out whether Integer already has a compareTo<Integer>() method, and whether it implements the Comparable<Integer> interface.
Find out whether your TreeMap has to be sorted or is sorted automatically.

I think once you have found all that lot out, your answer to your query will be very easy. Then try it out and tell us what happens.

CR
 
Campbell Ritchie
Sheriff
Pie
Posts: 49865
71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you need a Comparator at all?
CR
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you're missing the point -- he wants to sort on the value, not the key.

Leaving aside the question of whether this is a good idea or not, and just looking at it as a programming challenge: The Comparator is going to need a reference to the Map, so it can find the values for the keys it will be passed as arguments. Since the Comparator is a constructor argument to the Map, this will be a multi-step process. But basically, you could do something like this (untested



Let us know if you get this crazy scheme to work!
 
pradeep selvaraj
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah Ernest you are correct. I wanted to sort the treemap using the value instead of the key. I tried out using a treeset along with the treemap, Like this



Now, iterating through the set gives me the results sorted according to the Integer (ie the value field in the tree map). But when i try using the same comparator with the TreeMap directly(as show below), i get a type cast exception.




Yeah this sorthing could have been done simply by using a class that implements comparable, but my assignment required me to use data structures, that's why i had to do it this way.

Thanks

Serish
[ May 02, 2006: Message edited by: serish selvaraj ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic