The value of HashMap is not sequential, it is implemented according to the hashcode of key. How are we going to achieve this sort of unordered hashmap? (TreeMap similar)
Import Java.util.arraylist;import java.util.arrays;import Java.util.collections;import Java.util.Comparator;import Java.util.hashmap;import Java.util.list;import Java.util.map;import java.util.Map.Entry; map<string, long> map = new hashmap<string, long> (), Map.put ("C", 33333L), Map.put ("a", 11111L); Map.put ("D", 44444L); Map.put ("E", 55555L); Map.put ("B", 22222L);//Convert Map.entryset () to Listlist<map.entry<string, long> > list = new arraylist<map.entry<string, long>> (Map.entryset ()); Collections.sort (list, new comparator<map.entry<string, long>> () {//descending sort @overridepublic int compare ( Entry<string, long> O1, entry<string, long> O2) {//return o1.getvalue (). CompareTo (O2.getvalue ()); return O2.getvalue (). CompareTo (O1.getvalue ());}); For (map.entry<string, long> mapping:list) {System.out.println (Mapping.getkey () + ":" + mapping.getvalue ());}
Operation Result:
e:55555d:44444c:33333b:22222a:11111
How Java sorts HashMap by value