How can I get a sorted list of keys that are contained within a Map?

Brandon Rohlfs

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.

/* TreeMap used. Keys stored 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() + "	");
}
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact