Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort hashtable by values

Tags:

java

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?

like image 201
aherlambang Avatar asked Mar 03 '11 04:03

aherlambang


People also ask

How do you sort values in a Hashtable?

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.

Can Hashtable be sorted?

Sorry, but you can't sort hashtable. You will have to refactor your code to use some sortable collections.

Is Hashtable sorted in Java?

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.

Can we sort values in HashMap?

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.


1 Answers

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);
    }
like image 85
卢声远 Shengyuan Lu Avatar answered Oct 08 '22 07:10

卢声远 Shengyuan Lu