• Post Reply Bookmark Topic Watch Topic
  • New Topic

adding to TreeMap and sorting it  RSS feed

 
Ally Summers
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • 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 ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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
  • 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:


 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!