Have a Question?
Print

01074: How to sort a Java Hashtable

Title:

How to sort a Java Hashtable.

Description:

This is from a post on the bbj-developers list that might be helpful: 

The easiest way to sort objects is to use a TreeMap. It is similar in it’s methods to a Hashtable but provides a sorted capability. You use the .put(key!,object!) method to add objects to the table and the .get(key!) to get them out by key. 

When you want to retrieve the items in key sequence you can use the .keySet() method of the TreeMap. This gives you a set of keys in the proper sequence. You can then load these into a BBj Vector using the addAll() method of the java List/Collections interfaces, which BBjVectors implement. Here is a code snip that reads a comma delimited file with US Zip (Postal) Codes, stores the information in a TreeMap, then retrieves the list of keys and adds them to a BBjVector. 

bbj!=bbjapi() 
zipTree!=new java.util.TreeMap() 
dim zip$:”zipCode:c(1*=44),city:c(1*=44),state:c(1*=44),county:c(1*=)” 
zip=unt;open(zip)”zipCode” 

while 1 
read(zip,err=*break)zip$ 
zipTree!.put(zip.zipCode$,zip$) 
wend 

rem create a BBj Vector 
rem fill vector from the set of keys in the TreeMap 

zipVector! = bbj!.makeVector() 
zipVector!.addAll(zipTree!.keySet()) 

The resulting vector is sorted in “Zip code” sequence. 

You can also read the data from the file and put it into a vector, then sort the vector. 

bbj!=bbjapi() 
zipVector!=bbj!.makeVector() 
dim zip$:”zipCode:c(1*=44),city:c(1*=44),state:c(1*=44),county:c(1*=)” 
zip=unt;open(zip)”zipCode” 

while 1 
read(zip,err=*break)zip$ 
zipVector!.addItem(zip.zipCode$) 
wend 

rem use the java.util.Collections.sort(list!) method to sort the vector 
java.util.Collections.sort(zipVector!) 

The vector, zipVector! is now sorted by zip code. The nice thing about this is that BBjVectors implement the Java List and Collection interfaces, so all of the methods available in these interfaces are also available for vectors. Therefore we can use the .addAll(list!) method or the sort(list!) method as shown, with BBj Vectors. 



Last Modified: 12/31/2004 Product: BBj Operating System: All

BASIS structures five components of their technology into the BBx Generations.

Table of Contents
Scroll to Top