• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

adding to TreeMap and sorting it

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Can anyone help me with this problem. I have a TreeMap with a user object as a key and a HashMap with exams as a value. Users have a unique id and a, possibly not unique, name. I add users to the map with a comparator:

So, the users are added to the TreeMap, based on the id and, also, sorted by id. However, when displaying the users, I need to sort them by name. If I create my TreeMap with a "name" comparator, then the users are not only sorted by name, but also grouped by name, so "Ann Smith" and "Peter Smith" are considered as the same user (name="Smith"). I searched through existing topics on TreeMaps, but couldn't find a similar situation...

[ July 21, 2006: Message edited by: Ally Summers ]
[ July 21, 2006: Message edited by: Ally Summers ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ally,

Welcome to JavaRanch!

You can't make the TreeMap change its sort key, but you can easily re-sort the collection on another key when you need to. For example, you might do something like this:

 
Ally Summers
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ernest,

Thank you so much for your fast reply.
It's so simple, but it makes such a difference!
For sorting I used:


reply
    Bookmark Topic Watch Topic
  • New Topic