• Post Reply Bookmark Topic Watch Topic
  • New Topic

Treemap sort based on Value.. is it possible?  RSS feed

 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

I know this topic has been discussed quite a few times but none of the posts were satisfactory.

I have legacy code with TreeMaps(key,value) used extensively. But I need to sort my TreeNodes based on "value" rather than "keys".

Is there a way to resort my TreeMap based on value? Or better still is there a way to sort the nodes of tree in some order?

Any suggestions, solutionsm, work arounds deeply appreciated

TIA
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can think of at least two ways to do this:

1) Create a new TreeMap and switch the Keys and Values from the old TreeMap. In pseudocode:


2) Create a List from the Set returned by entrySet() and use Collections.sort() and a custom Comparator to sort the Map.Entries in this List.

I'm not sure which I prefer. I've implemented #2 previously and it can get messy. If the values already implement Comparable then #1 seems cleaner. Otherwise, you will need a custom Comparator there as well.

HTH

Layne
 
Ravi Sathish
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Layne

I actually did not extensive search. This topic was discussed previously here:

Sorting TreeMap based on Value instead of Keys

I implemented Option # 2 too

I'll try option 1
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!