I have a TreeMap which is sorted by key. However I have requirement to sort by value instead. Can I do this using a comparator? Can someone give me code example? I am relatively new to Java.
Well, you can't sort the keys AND the values in the same data structure. You could extract the values into a TreeSet. They would then be sorted and you could iterate through them:
TreeMap map = new TreeMap();
...
TreeSet set = new TreeSet(map.values());
Iterator i = set.iterator();
// Now iterate through the sorted elements
Of course, this assumes that the values in your TreeMap implement the Comparable interface...
At this point, you will probably need to actually tell me what problem it is that you are trying to solve or how you are trying to use the data. Otherwise, I am just shooting in the dark.
Please elaborate on what data is being stored and what you are trying to do with it.
Here is a sample data... that I have inserted in TreeMap
ABC America
AEN Netharlands Ando
AND Andaman
BEC Barbados
NED Netherlands
EJB returns resultset of above data that has been loaded into a TreeMap. Just to give you some history...
We tried using simple Map and added sort to SQL but that doesn't work. So we decided to use TreeMap. However TreeMap sorts by Key. So when I transform it to HTML this is how it looks
<OPTION value="ABC">America</OPTION>
<OPTION value="AEN">Netherlands Ando</OPTION>
<OPTION value="AND">Andaman</OPTION>
<OPTION value="BEC">Barbados</OPTION>
<OPTION value="NED">Netherlands</OPTION>
and hence the order doesn't work well, bcos I want to sort by description and not code.
i.e. I want to sort by value in Map.
I hope I have explained well. Please let me know if you have further questions.
Ok, here is some code that essentially reverses the TreeMap, i.e. it swaps the values with the keys so that the new Treemap is sorted by the values of the previous tree. Of course, this means that the keys become the values and vice versa but this shouldn't matter to you for output purposes. You can then use the iterator to populate your HTML code dynamically via a servlet of jsp or whatever.
Since a TreeMap is guaranteed to have log(N) lookup and insertion, this is relatively inexpensive, i.e. O(nlogn)
public static TreeMap keysToValues(TreeMap t)
{
// Create map to be returned
TreeMap newmap = new TreeMap();
// Get the keys from the incoming TreeMap
Set keys = t.keySet();
Iterator i = keys.iterator();
String key = null;
//Extract key/value pairs and insert in new Tree
while (i.hasNext())
{
key = (String)i.next();
newmap.put(t.get(key), key);
}
return newmap;
}
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.