• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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
 
Evacuate the building! Here, take this tiny ad with you:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic