Package Corejava;import Java.util.arraylist;import Java.util.collections;import java.util.comparator;import Java.util.hashmap;import java.util.linkedhashmap;import java.util.list;import Java.util.Map;import java.util.Set; Import Java.util.map.entry;public class Sorts the Map by value {public static void main (string[] args) {//Build test Data map<string, integer> map = new hashmap<string,integer> () map.put ("G", 7), Map.put ("a", 6), Map.put ("B", 5), Map.put ("C", 4); Map.put ("D", 3); Map.put ("F", "1"), Map.put ("E", 2);//Sort map, sort by value in ascending order map = Sortmapbyvalue (map);//test Code//set< entry<string,integer>> set = Map.entryset ();////for (entry<string, integer> entry:set) {// System.out.println (Entry.getkey () + ":" +entry.getvalue ());//}}/** * Sorts the map, sorts it in ascending order of value * @param map * @return */public Static map<string,integer> Sortmapbyvalue (map<string,integer> map) {//transforms the map collection into a list collection, The purpose is to call the Collections.sort method to sort the list. The object in//list is a entry, the key-value pair of the map. Set<entry<string,integer>> Set = Map.entryset (); list<entry<string,integer>> list = new Arraylist<entry<string,integer>> (set),//sort overloaded method, By implementing the Comparator interface to sort the Entry elements in the list collection, sort them in ascending order by Entry value Collections.sort (list, new comparator<entry< String,integer>> () {@Overridepublic int compare (entry<string, integer> o1,entry<string, integer> O2 {return O1.getvalue ()-O2.getvalue ();}}); /Create a Linkedhashmap, in order to return an ordered map, in the order that the elements are placed in the map map<string,integer> resultmap = new linkedhashmap< String,integer> (); for (entry<string, integer> e:list) {resultmap.put (E.getkey (), E.getvalue ());} return resultmap;}}
Ideas:
1. Turn map into a list that can be sorted
2. Use the overloaded method of Collections.sort to implement the Compactor interface for custom sorting, sorted by the value of map in ascending order.
3. Return an ordered map
Sort according to the value of map