How to sort a Java Hashtable?

一世执手 提交于 2019-12-23 07:59:49

问题


I inserted some data into a Java Hashtable. If I read the data from the Hashtable it doesn't come back in the same order that I inserted it in. How do I get the ordered data from the Hashtable?

I use the following code to get the values from the hashtable:

// Get a set of the entries
Set set = hsUpdateValues.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
    Map.Entry me = (Map.Entry) i.next();            
    System.out.print(
        "Key : " + me.getKey()
        + ", Value: " + me.getValue()
    );
}

回答1:


If you want an order-preserving map, you should use LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap.

Note that this is usually compared with HashMap rather than Hashtable - I don't know of an order-preserving equivalent to Hashtable; the latter isn't usually used these days anyway (just as ArrayList is usually used in preference to Vector).

I've assumed you want insertion order rather than key-sorted order. If you want the latter, use TreeMap.




回答2:


Although a Hashtable cannot be sorted, he asked how to get sorted data, that can be done sorting the list of keys extracted from the HashTable and retrieving values in that order. Something like:

List<'your_type'> tmp = Collections.list('your_hashtable'.keys());
Collections.sort(tmp);
Iterator<'your_type'> it = tmp.iterator();

while(it.hasNext()){
    'your_type' element =it.next();
    //here you can get ordered things: 'your_hashtable'.get(element);
}

will be fine.




回答3:


A Hashtable has no predictable iteration order, and cannot be sorted. If you only want predictable iteration order you should use a LinkedHashMap. If you want to be able to sort your Map, you should use a TreeMap.




回答4:


Use TreeMap for sorting it:

Map<String, String> yourMap = new HashMap<String, String>();
    yourMap.put("1", "one");
    yourMap.put("2", "two");
    yourMap.put("3", "three");

Map<String, String> sortedMap = new TreeMap<String, String>(yourMap);



回答5:


Hashtable is a legacy collection which was replaced by Java 1.2 collections in 1998. I suggest you avoid it, along with Vector and Enumeration.

Instead of Hashtable use HashMap where possible. You can add synchronization using Collections.synchronizedMap(map) if you need it.

Instead of Vector, use ArrayList where possible. You can add synchronization using Collections.synchronizedList(map) if you need it.

Instead of Enumeration you can use Iterator or even a for-each loop.




回答6:


If i read the data from the hash table it's not coming in the same order what i inserted.

Your question does not make sense. A Hashtable does not have an "order", it is unordered (Edit: Some implementations do have an order, but it's not common for a hashtable)..

In what order would you expect the entries to be?

If you want to store elements in a certain order, you need to use a list (e.g. a subclass of java.util.List).

And BTW, your code sample does not even contain a hash table.




回答7:


I have written an elaborate answer about sorting and ordered retrieving of Maps in this previous Question:

Accessing the last entry in a Map



来源:https://stackoverflow.com/questions/4333265/how-to-sort-a-java-hashtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!