Sort a hash table by values

If I have a Hashtable and I want to sort it by value, that is:: integer in descending order. How can I do this and be able to print across the entire key-value pair?

+5
source share
6 answers

Move to 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);
    }
+13
source

Hash tables are not sorted. Therefore, you need to make a copy of the key set of the hash table, sort it and get the values ​​from the hash table, iterate using the keys in the sorted list.

Or use a sorted hash table, such as TreeMap; to avoid copying a copy of the key set.

0
source

" ", TreeMap, ArrayList, .

" ", , , , .

.

0

SortedMap , , , . :

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

.

HashMap

How to sort a treemap based on its values?

Both are implementations for sorting a hash map based on a value in ascending or descending order.

0
source

Ineffective way to do this if you do not understand the code above.

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
source

All Articles