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?
Before moving forward, we need to understand that it is not possible to sort a Hashtable since the data is stored by the hashcode of the key, not by the index . So to sort the data of a Hashtable, we need to have a sortable object like an array or an ArrayList. Sorting has to be done on Key or Value.
Sorry, but you can't sort hashtable. You will have to refactor your code to use some sortable collections.
Hashtable is a data structure that stores data in key-value format. The stored data is neither in sorted order nor preserves the insertion order.
HashMaps are a good method for implementing Dictionaries and directories. Key and Value can be of different types (eg - String, Integer). We can sort the entries in a HashMap according to keys as well as values.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With