File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Hash Table - Sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Hash Table - Sorting" Watch "Hash Table - Sorting" New topic

Hash Table - Sorting

Vishnu Prakash
Ranch Hand

Joined: Nov 15, 2004
Posts: 1026

I had created a HashTable instance with entries in it. I know HashTable class doesn't support sorting. But I need the key/value to be sorted in someway. TreeMap class supports sorting. But I don't know how to use it. Please help to sort the entries.

Servlet Spec 2.4/ Jsp Spec 2.0/ JSTL Spec 1.1 - JSTL Tag Documentation
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

TreeMaps sort entries by key, based on the "natural order" of the key. What that means is that whatever object you use as a key must implement the Comparable interface. This is an interface which defines the compareTo(Object o) method, so the implementing object will have to implement how you decide one object needs order after another.

The easiest way to use a TreeMap is to use a Key which already implements Comparable - Strings, Integers, Longs etc. are the most obvious. Assuming you do this, you know that as you put object into the TreeMap, they are ordered as defined by the key's natural order.
[ March 01, 2005: Message edited by: Paul Sturrock ]

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
jQuery in Action, 3rd edition
subject: Hash Table - Sorting
It's not a secret anymore!