Java TreeMap重写Comparator降序排列
TreeMap中默认的排序为升序,如果要改变其排序可以自己写一个Comparator。
重写comparator:
class descendComparator implements Comparator { public int compare(Object o1,Object o2) { Double i1=(Double)o1; Double i2=(Double)o2; return -i1.compareTo(i2); } }
TreeMap降序例子:
TreeMap<Double,Integer> map = new TreeMap<Double,Integer>(new descendComparator()); map.put(1.1, 1); map.put(1.2, 2); map.put(2.2, 4); Set<Double> keys = map.keySet(); Iterator<Double> iter = keys.iterator(); while(iter.hasNext()) { double a = iter.next(); System.out.println(" "+a+":"+map.get(a)); }
运行结果
2.2:4 1.2:2 1.1:1
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。