简体   繁体   中英

sort hashtable by values

If I have a Hashtable and I want to sort it by the value, ie: integer in a descending order. How can I do this and be able to print through 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);
    }

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;
        }
    }


}

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.

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());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM