• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Treemap sort based on Value.. is it possible?

 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Drove my Chevy to the levee but the levee was dry. A wrung this tiny ad and it was still dry.
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic