Sort TreeMap

Discussion in 'Java' started by Ben, Apr 27, 2006.

  1. Ben

    Ben Guest

    Hi,

    I have a TreeMap with the keys being numbers stored as Strings. I have
    made it sorted it, however it sorts it as 1, 10, 11, etc and not 1, 2,
    3. What is the simplest way to sort it be arranged as 1, 2, 3.

    Thanks in advance.

    Ben.
     
    Ben, Apr 27, 2006
    #1
    1. Advertising

  2. Ben wrote:
    > Hi,
    >
    > I have a TreeMap with the keys being numbers stored as Strings. I have
    > made it sorted it, however it sorts it as 1, 10, 11, etc and not 1, 2,
    > 3. What is the simplest way to sort it be arranged as 1, 2, 3.


    Don't store the numbers as strings, but as numbers. Alternatively, waste
    some time, write your own Comparator and use that in the constructor.

    /Thomas

    --
    The comp.lang.java.gui FAQ:
    ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
    http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
     
    Thomas Weidenfeller, Apr 27, 2006
    #2
    1. Advertising

  3. Ben

    Simon Guest

    Ben wrote:
    > I have a TreeMap with the keys being numbers stored as Strings. I have
    > made it sorted it, however it sorts it as 1, 10, 11, etc and not 1, 2,
    > 3. What is the simplest way to sort it be arranged as 1, 2, 3.


    The best solution would probably be to use Integers instead of the Strings as
    the keys. However, if you don't want that, you can pass a Comparator to the
    constructor of TreeMap that takes care of the ordering.

    Cheers,
    Simon
     
    Simon, Apr 27, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ahmed Moustafa

    HashMap vs TreeMap

    Ahmed Moustafa, Aug 9, 2003, in forum: Java
    Replies:
    2
    Views:
    46,507
    Roedy Green
    Aug 10, 2003
  2. Harry

    TreeMap problem...

    Harry, Sep 22, 2003, in forum: Java
    Replies:
    3
    Views:
    496
    Harry
    Sep 23, 2003
  3. Wendy S
    Replies:
    4
    Views:
    14,271
    Jim McMaster
    Feb 19, 2004
  4. Miguel Angel
    Replies:
    9
    Views:
    14,372
    Christian Kaufhold
    Apr 15, 2004
  5. Navin
    Replies:
    1
    Views:
    765
    Ken Schaefer
    Sep 9, 2003
Loading...

Share This Page