Package com.demo.base;
Import Java.util.Comparator;
Import Java.util.TreeMap;
public class Test {
public static void Main (string[] args) {
Do not specify a sequencer
treemap<string, string> treeMap1 = new treemap<string, string> ();
Treemap1.put ("2", "1");
Treemap1.put ("B", "1");
Treemap1.put ("1", "1");
Treemap1.put ("A", "1");
System.out.println ("treemap1=" +treemap1);
Specifying the Sequencer
treemap<string, string> treeMap2 = new treemap<string, string> (new comparator<string> () {
/*
* int Compare (object O1, Object O2) returns the integral type of a primitive type,
* Returns a negative number indicating: O1 is less than O2,
* Returns 0 means: O1 and O2 are equal,
* Returns a positive number indicating: O1 is greater than O2.
*/
public int Compare (string O1, string O2) {
Specifies that the sequencer is sorted in descending order
Return O2.compareto (O1);
}
});
Treemap2.put ("2", "1");
Treemap2.put ("B", "1");
Treemap2.put ("1", "1");
Treemap2.put ("A", "1");
System.out.println ("treemap2=" +TREEMAP2);
}
}
Execution output:
- treemap1={1=1, 2=1, a=1, b=1}
- treemap2={b=1, a=1, 2=1, 1=1}
Summary:
1, TreeMap If the sequencer is not specified, the default will be sorted by the key value in ascending order, if the sequencer is specified, the order is sorted by the specified sequencer.
2, the specific collation, developers can be specified in the int compare () method.
TreeMap Sort by key