Java hashmap sorted by value

Source: Internet
Author: User

/**
* Sort public static <t> void sort (T [] A, comparator <? Super T> C)
* Sorts the array of specified objects based on the Generation sequence of the specified comparator. All elements in the array must be comparable by specifying the comparator (that is, for any E1 and E2 elements in the array
* For elements, C. Compare (E1, E2) cannot throw classcastexception ). This sorting is ensured to be stable: sort is not called
* Method to re-Sort equal elements. This sort algorithm is a modified merge sort algorithm.
* (If the highest element in the lower sublist is smaller than the lowest element in the upper sublist, the merge is ignored ). This algorithm provides guaranteed N * log (n) performance. Parameter:-
* Array C-the comparator that determines the array order. The null value indicates that the natural sequence of elements should be used. Throw: classcastexception-
* If the array contains elements that cannot be compared with each other using the specified comparator.
*
* @ Param H
* @ Return: sort the MAP values in ascending order.
*/
@ Suppresswarnings ({"unchecked", "rawtypes "})
Public static map. Entry [] getsortedhashtablebyvalue (MAP h ){
Set set = H. entryset ();
Map. Entry [] entries = (Map. Entry []) set. toarray (new map. Entry [Set
. Size ()]);
Arrays. Sort (entries, new comparator (){
Public int compare (Object arg0, object arg1 ){
Long key1 = long. valueof (Map. Entry) arg0). getvalue ()
. Tostring ());
Long key2 = long. valueof (Map. Entry) arg1). getvalue ()
. Tostring ());
// Ascending
// Return key1.compareto (key2 );
// Descending order
Return key2.compareto (key1 );
}
});

Return entries;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.