- import java.util.Comparator;
- import java.util.TreeMap;
- public class Main {
- publicstaticvoid main(String[] args) {
- TreeMap<Integer,Integer> map1 = new TreeMap<Integer,Integer>(); //The default TreeMap is sorted in ascending order
- TreeMap<Integer,Integer> map2= new TreeMap<Integer,Integer>(new Comparator<Integer>(){
- /*
- * int compare(Object o1, Object o2) returns a primitive integer,
- * Return a negative number to indicate: o1 is less than o2,
- * Return 0 means: o1 and o2 are equal,
- * Returns a positive number indicating: o1 is greater than o2.
- */
- publicint compare(Integer a,Integer b){
- return b-a;
- }
- });
- map2.put(1,2);
- map2.put(2,4);
- map2.put(7, 1);
- map2.put(5,2);
- System.out.println("Map2="+map2);
- map1.put(1,2);
- map1.put(2,4);
- map1.put(7, 1);
- map1.put(5,2);
- System.out.println("map1="+map1);
- }
- }