开发者

Sort HashTable according to values(numeric) preferably descending order and maintain the key-value

I have the following key-value pairs in my HashTable.

    KEY : VALUES
    12345:45;
    23456:23;
    23445:34;
    12367:101;

    Output should be:
    12367:101;
    12345:45;
    23445:34;
    23456:23;

i.e. the output is in the descending order of the values.

ht_sort is my Hash table containing the key-value pairs.

开发者_如何学C//get the values from the hashtable as array objects.
Object[] arytf= ht_sort.values().toArray();

//Sort the array objects.
Arrays.sort(arytf);

But the problem is that I am unable to link back these sorted values to the hash to get the keys.

I am not exactly sure how to go about doing this, I have checked the previous threads but couldnot make anything out of them. Looking for help on this.

Thanks.


You could sort the entries in the hash table instead, with a custom implementation of Comparator<Map.Entry<...>> which just compared the values. Then you'd have a sorted array of entries, and you can just iterate over them picking out both keys and values as you go.

EDIT: As noted, the Map.Entry values are somewhat transient - so you probably want to create a pair to collect the two. (If you're dealing with non-generic types, you could always create an Object[2] to store the key in index 0 and the value in index 1...) Copy the entries as you iterate and then sort the resulting array.


EDIT: Duplicated values allowance solution:

List<Map.Entry<Integer, Integer>> sortMapValues2(Map<Integer, Integer> map){
    //Sort Map.Entry by value
    List<Map.Entry<Integer, Integer>> result = new ArrayList(map.entrySet());
    Collections.sort(result, new Comparator<Map.Entry<Integer, Integer>>(){
        public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
            return o2.getValue() - o1.getValue();
    }});

    return result;  
}

You could get lots of articles by google "java collections framework".


Once your array is sorted, iterate through it and call _yourHash.get(arytf[n])


If you just want to store sorted key/value pairs, you can take a look at LinkedHashMap:

http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

My solution would be to sort an Entry array (for example, using a custom Comparator) and then insert them in proper order into a LinkedHashMap.


http://www.xinotes.org/notes/note/306/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜