代码示例:
public class TestMap { //定制排序 @Test public void test5(){ Comparator com = new Comparator() { @Override public int compare(Object o1, Object o2) { if (o1 instanceof Customer && o2 instanceof Customer) { Customer c1 = (Customer) o1; Customer c2 = (Customer) o2; int i = c1.getId().compareTo(c2.getId()); if (i == 0){ return c1.getName().compareTo(c2.getName()); }else { return i; } } return 0; } }; TreeMap map = new TreeMap(com); map.put(new Customer("AA",1001),89); map.put(new Customer("CC",1001),79); map.put(new Customer("MM",1004),99); map.put(new Customer("GG",1002),69); Set key1 = map.keySet(); for (Object obj : key1) { System.out.println(obj + "--->" + map.get(obj)); } } //自然排序 @Test public void test4(){ Map map = new TreeMap(); map.put(new Person("AA",23),89); map.put(new Person("MM",22),79); map.put(new Person("GG",23),99); map.put(new Person("JJ",13),69); Set key1 = map.keySet(); for (Object obj : key1) { System.out.println(obj + "--->" + map.get(obj)); } } }
结果1:
Customer{name='AA', id=1001}--->89
Customer{name='CC', id=1001}--->79
Customer{name='GG', id=1002}--->69
Customer{name='MM', id=1004}--->99结果2:
Person{name='JJ', age=13}--->69
Person{name='MM', age=22}--->79
Person{name='AA', age=23}--->89
Person{name='GG', age=23}--->99
总结:
TreeMap:按照添加进Map中的元素的key的指定属性进行排序。要求:key必须是同一个类的对象!
针对key:自然排序 vs 定制排序