problemMap<key,value> How to sort based on value values
Essence Answer
Method 1:Using TreeMap, you can refer to the following code
public class Testing {public static void main (string[] args) {hashmap<string,double> map = new HASHMAP&L T String,double> (); Valuecomparator BVC = new Valuecomparator (map); treemap<string,double> Sorted_map = new treemap<string,double> (BVC); Map.put ("A", 99.5); Map.put ("B", 67.4); Map.put ("C", 67.4); Map.put ("D", 67.3); SYSTEM.OUT.PRINTLN ("unsorted map:" +map); Sorted_map.putall (map); System.out.println ("Results:" +sorted_map); }}class Valuecomparator implements comparator<string> {map<string, double> base; Public Valuecomparator (map<string, double> base) {this.base = base; }//Note:this comparator imposes orderings that is inconsistent with equals. public int Compare (string A, string b) {if (Base.get (a) >= Base.get (b)) {return-1; } else {return 1; }//Returning 0 would merge keys}}If you do not write your own comparator,treemap default is to sort by key
Method 2:
public class maputil{Public static <k, V extends comparable<? Super v>> Map<k, v> sortbyvalue ( Map<k, v> map) { list<map.entry<k, v>> List = new linkedlist<map.entry<k, v> > (Map.entryset ()); Collections.sort (list, new comparator<map.entry<k, v>> () {public int compare (map.entry<k, V > O1, map.entry<k, v> O2) {return (O1.getvalue ()) . CompareTo (O2.getvalue ()); } ); map<k, v> result = new linkedhashmap<k, v> (); For (map.entry<k, v> entry:list) { result.put (Entry.getkey (), Entry.getvalue ()); } return result;} }
These two methods, I simply tested the next, if the map size at level 100,000 above, both time is hundreds of milliseconds, the second method will be faster. Otherwise, the first method is a little faster. So if you are dealing with a map that is hundreds of thousands of levels below the size, two ways to use freely, to see personal likes.
StackOverflow Link: Http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
Column Introduction:very like StackOverflow, can always find a solution to the problem of incurable diseases. Accidentally found that the site has a list of heat. So select some of the higher heat problems, and then according to their own understanding, the discussion of the people to comb out. Therefore, these articles are not true translation, but in accordance with their own understanding of a number of additions and deletions, polishing, hoping to put the above discussion, more streamlined and effective sharing to everyone. if you want to reprint, please specify the original addressHttp://blog.csdn.net/lizeyang
"StackOverflow Good question" map<key,value> sort based on value values