Reputation: 14418
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?
Upvotes: 7
Views: 39488
Reputation: 417
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;
}
}
}
Upvotes: 0
Reputation: 7016
Refer to below link
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
Upvotes: 0
Reputation: 32004
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);
}
Upvotes: 16
Reputation: 2201
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());
}
Upvotes: 1
Reputation: 210445
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.
Upvotes: 0
Reputation: 9903
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.
Upvotes: 0