TreeMap the bottom layer is based on the red and black tree data structure, the default is based on the natural sort of key to organize (such as the size of the integer, String dictionary sort). Therefore, TreeMap can only be sorted by key, and cannot be sorted according to value (otherwise the key will not be sorted at all to form TreeMap).
Today there is a need to sort by the value in TreeMap. So the online look, the general idea is to convert treemap entryset into a list, and then use collections.sor sort. Code:
[Java]View PlainCopy
- Public static void Sortbyvalue () {
- map<string,string> map = new treemap<string,string> ();
- Map.put ("A", "dddd");
- Map.put ("D", "AAAA");
- Map.put ("B", "CCCC");
- Map.put ("C", "bbbb");
- list<entry<string, string>> list = new arraylist<entry<string, string>> (Map.entrySet ());
- Collections.sort (list,new comparator<map.entry<string,string>> () {
- //Ascending sort
- public int Compare (entry<string, string> O1, entry<string, string> O2) {
- return O1.getvalue (). CompareTo (O2.getvalue ());
- }
- });
- for (entry<string, string> e:list) {
- System.out.println (E.getkey () +":" +e.getvalue ());
- }
- }
Running Result: d:aaaa
c:bbbb
B:cccc
A:dddd
TreeMap Sort By value