6

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 through all of the key - value pair?

aherlambang
  • 14,290
  • 50
  • 150
  • 253
  • 1
    `HashTable`, or `HashMap`? Why are you using `HashTable` anymore? – Matt Ball Mar 03 '11 at 04:50
  • 3
    Whoa, there's a class called `HashTable` in Java? I learned something new today! – user541686 Mar 03 '11 at 04:50
  • Oh I wasn't talking about the capitalization -- I just never knew that one existed. :) – user541686 Mar 03 '11 at 05:07
  • @Matt Ball - he might have been using Java ME, which doesn't have the Java Collections framework ... in some profiles. But apparently not, since he's accepted a solution that depends on `Map` and `Collections`. – Stephen C Mar 03 '11 at 05:35

6 Answers6

15

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);
    }
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
  • 1
    This will sort in ascending order, not descending order. o1 and o2 should be swapped in the return of the compare function. – Paul Oct 22 '12 at 22:32
  • throws classcast exception on the return line for a Hashtable and an ArrayList> String cannot be cast to Integer. What's wrong? cannot get it. – SuppressWarnings Dec 18 '14 at 10:48
1

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());
    }
Melv
  • 2,201
  • 16
  • 14
  • 3
    This answer is wrong... this explains how to sort by key. The original question was how to sort by value. – Dave B Jul 20 '14 at 17:18
0

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

Community
  • 1
  • 1
Rais Alam
  • 6,970
  • 12
  • 53
  • 84
0

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


}
happs
  • 417
  • 6
  • 15
0

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.

vanza
  • 9,715
  • 2
  • 31
  • 34
  • the value is the one which is going to be sorted.. so I need to get the key from the value... is it even possible? – aherlambang Mar 03 '11 at 05:03
0

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.

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
  • you mean add all of the value in the hashtable to a TreeMap? if that's so then how can I print the key along with the value? – aherlambang Mar 03 '11 at 04:58
  • You add the values to the TreeMap using the keys already in the hashtable, then you iterate through the TreeMap's keys and print each key and value. – user541686 Mar 03 '11 at 05:06