开发者

sort hashtable by values

开发者 https://www.devze.com 2023-02-14 07:25 出处:网络
If I have a Hashtableand I want to sort it by the value, i.e: integer in a descending order. How can I do this and be able to print thro开发者_运维知识库ugh all of the key - value pair?Transfer as Lis

If I have a Hashtable and I want to sort it by the value, i.e: integer in a descending order. How can I do this and be able to print thro开发者_运维知识库ugh all of the key - value pair?


Transfer as List and sort it:

    public static void sortValue(Hashtable<?, Integer> t){

       //Transfer as List and sort it
       ArrayList<Map.Entry<?, Integer>> l = new ArrayList(t.entrySet());
       Collections.sort(l, new Comparator<Map.Entry<?, Integer>>(){

         public int compare(Map.Entry<?, Integer> o1, Map.Entry<?, Integer> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }});

       System.out.println(l);
    }


SortedMap allows you to either specify a comparator, or if not use the natural ordering of elements, of which the inverse will be fine for Integers. The following prints in descending sorted order:

    SortedMap<Integer, Object> map = new TreeMap<Integer, Object>(new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    });
    map.put(2, "value2");
    map.put(3, "value3");       
    map.put(1, "value1");
    for (Map.Entry<Integer, Object> nextEntry : map.entrySet()) {
        System.out.println(nextEntry.getKey() + " : " + nextEntry.getValue());
    }


Hashtables are not sorted. So you need to make a copy of the hash table's key set, sort it, and retrieve the values from the hashtable by iterating through the keys in your sorted list.

Or use a sorted hash table substitute, such as TreeMap; that would avoid having to make the copy of the key set.


If you really mean "how do I do this", then the answer is to just add all of them to a TreeMap and then iterate through it, or add all of them to an ArrayList and then sort it.

If you mean "how do I do this efficiently", I believe the answer is that it's not possible to get any more efficient than above.

This question may have some more info.


Refer to below link

Sorting HashMap by values

or

How to sort a treemap based on its values?

Both are implementation for sorting an hashmap based on value in ascending or descending order


An inefficient way of doing it if you don't understand the above code.

public static void sortHashtable1 (Hashtable <Integer,Double> t,int count)
{
    double a[]=new double[count];
    int i=0;
    for (int ss : t.keySet())
    {
        a[i]=t.get(ss);
        i++;
    }
    Arrays.sort(a);
    outer:for(int j=a.length-1;j>=0;j--)
    {
        for(int ss : t.keySet())
        if(t.get(ss)==a[j])
        {
            System.out.println(ss+" "+a[j]);
            a[j]=-1;
            t.put(ss, -1.0);
            continue outer;
        }
    }


}
0

精彩评论

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