Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Ordering first 4 keys in TreeMap / Comparator question  RSS feed

 
Norman Rozental
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a TreeMap of currencies. Keys are ("USD", "EUR"...) and each value holds some collection.

I want to sort the TreeMap so that "GBP", "USD", "CAD" and "EUR" are the first 4 keys in the map and other currencies are in their natural order following these 4 keys. I don't know which currency I'll be getting from a certain operation so it could be that "USD" is encountered last which means it will be the last key in my TreeMap.

How would I do this using the Comparator and compareTo method?

Any help would be greatly appreciated.

Cheers
Norm.
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Erhm... Why do you need the keys in that order? I suppose you could write a comparator that specifically compares them to go in that order, but that seems like a rather round about way. If you need to access the keys in that order, why not just access the keys in that order? You could make an array

final String[] KEYS = {"USD","CAD"...};, and then when accessing elements in the map just iterate through KEYS. Or, perhaps the most elegant solution of all would be to just make a class Currency, which would have a String and an int (and whatever else you want). you would then say

final Currency USD=new Currency("USD",1);

and then the comparator would just go by the int, thus ordering these as keys.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know which currency I'll be getting from a certain operation so it could be that "USD" is encountered last which means it will be the last key in my TreeMap.

That makes this sounds suspiciously like homework, but I'll give you the benefit of the doubt.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!