• 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

Ordering first 4 keys in TreeMap / Comparator question

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic