Background
The implementation class TreeMap of SortedMap can traverse the key (key) in natural order or in custom order, sometimes we need to sort by values (value), this article provides a simple implementation idea.
Realize
Comparator interface
When using the value sort, the TreeMap implementation class is still used, except that the comparator implementation needs to be introduced in the TreeMap constructor.
TreeMap Constructors
Valuecomparator is the implementation of the comparator interface, which contains a common map object as a member variable and does a bit of work in the Compare method. That is, in the Compare method, the comparison of key is converted to a comparison of value.
- Limitations
This way only the map can be sorted, not a single key-value map can be added.
Import Java.util.comparator;import java.util.hashmap;import java.util.map;import java.util.treemap;/** * Created by Liutingna on 2017/9/30. */public class Testcomparator {class Valuecomparator implements comparator<string> {map<string, long& Gt Base Comparator external Comparator public valuecomparator (map<string, long> base) {this.base = base; }//Compare the values of the map to public int compare (string A, string b) {return Base.get (a). CompareTo (Base.get (b) ); }} public static void Main (string[] args) {map<string, long> Map = new hashmap<> (); Testcomparator testcomparator = new Testcomparator (); Testcomparator.valuecomparator valuecomparator = testcomparator.new valuecomparator (map); map<string, long> keysortmap = new treemap<> (); map<string, long> valuesortmap = new treemap<> (valuecomparator); Map.put ("AAA", 15L); Map.put ("Bxw", 13L); Map.put ("abc", 14L); Map.put ("BBB", 18L); SYSTEM.OUT.PRINTLN (map);//{aaa=15, bxw=13, abc=14, bbb=18}//Compare Keysortmap.putall by key (map); System.out.println (Keysortmap);//{aaa=15, abc=14, bbb=18, bxw=13}//Compare Valuesortmap.putall (map) based on value;// Valuesortmap.put ("CCC", 17L);//nullpointerexception, this way you can only sort the map, not add a single key-value map System.out.println (valu ESORTMAP);//{bbb=18, aaa=15, abc=14, Bxw=13}}}
Related information
The difference between comparable and comparator
To sort objects in a map based on value