Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

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

Dillinger4

Dazed Member
Joined
Oct 13, 1999
Messages
3,418
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");
}
 

finn0013

New member
Joined
Jan 11, 2001
Messages
222
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);
 
Top