Java中map的种类很多,java.util包中按照键值排序的容器为TreeMap。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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-07-26
  • 2021-08-18
  • 2022-02-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案