Results 1 to 2 of 2

Thread: How to get a sorted list of keys that are contained within a Map

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    How to get a sorted list of keys that are contained within a Map

    The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set might not contain it's elements (keys) in sorted order. For instance the HashMap class makes no guarantees as to the order of the elements contained within. Whereas the TreeMap class does guarantee element ordering since it implements the SortedMap interface.
    Code:
    /*TreeMap used. Keys should be in ascending order */
    
    Map<String,String> book = new TreeMap<String,String>(); 
    book.put(new String("Java"),new String("A trademark used for a programming language designed to develop applications, especially ones for the Internet, that can operate on different platforms."));
    book.put(new String("C#"),new String("An object-oriented language devised and promoted by Microsoft, intended to replace Java, which it strongly resembles."));
    book.put(new String("Python"),new String("A simple, high-level interpreted language by Guido van Rossum"));
    book.put(new String("LISP"),new String("A programming language designed to process data consisting of lists. It is widely used in artificial intelligence research.")); 
     
    Set words = book.keySet();
    for(Iterator i = words.iterator();i.hasNext();){
     System.out.print(i.next() + "\t");
    }

  2. #2
    Addicted Member finn0013's Avatar
    Join Date
    Jan 2001
    Location
    Charleston, SC
    Posts
    222

    Re: How to get a sorted list of keys that are contained within a Map

    Try the below code - it will give you a string array sorted using the compareTo method. If the key you are using is a different object type just do the same thing but make sure it implements the Comparable interface. I didn't compile this so you may need to tweak it to get rid of any compilation errors...

    Code:
    Set keys = myMap.keySet();
    String[] strkeys = keys.toArray(new String[keys.size()]);
    Arrays.sort(strkeys);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width