How do I do this?

Discussion in 'Java' started by tim@nocomment.com, Feb 10, 2007.

  1. Guest

    I am trying to use an array of some sort which will allow me to access
    a value based on a key (like in a Hashtable) but also allow me to
    access all entries sorted by the key.
    I have heard all kinds of solutions proposed but there seems to be
    nothing as straight forward as there should be.
    Can anyone give me some sample code where the table or tree or
    whatever is accessed by both the key and iterated through in key
    order?

    Thanks
    , Feb 10, 2007
    #1
    1. Advertising

  2. Nigel Wade Guest

    wrote:

    > I am trying to use an array of some sort which will allow me to access
    > a value based on a key (like in a Hashtable) but also allow me to
    > access all entries sorted by the key.
    > I have heard all kinds of solutions proposed but there seems to be
    > nothing as straight forward as there should be.
    > Can anyone give me some sample code where the table or tree or
    > whatever is accessed by both the key and iterated through in key
    > order?
    >
    > Thanks


    Won't SortedMap do what you want? It should be sorted according to the [natural]
    sorting order of whatever object you use for the key. Since the keys are
    sorted, if you iterate the SortedMap by key using keySet() method you should
    get the items back according to the sorting order of the keys.

    TreeMap<KeyObject,ItemObject> sortedMap = new TreeMap();
    //populate your map with items...
    for(KeyObject key : sortedMap.keySet()) {
    ItemObject item = sortedMap.get(key);
    }

    --
    Nigel Wade, System Administrator, Space Plasma Physics Group,
    University of Leicester, Leicester, LE1 7RH, UK
    E-mail :
    Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555
    Nigel Wade, Feb 12, 2007
    #2
    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.

Share This Page