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.
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
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.