Java中treeMap的使用

来源:互联网 发布:python 计算 macd 编辑:程序博客网 时间:2024/05/17 23:24

众所周知,TreeMap是一种可以用key来排序的map,下面说一下如何使用。

第一步 定义1个  实现Comparator接口,重载 public int compare(Step o1, Step o2) 方法 或静态类 

如下:

[java] view plain copy
print?
  1. static Comparator comparator1 = new Comparator() {    
  2.   
  3.       public int compare(Object o1, Object o2) {    
  4.       return Integer.parseInt(o2.toString()) - Integer.parseInt(o1.toString());    
  5.       }    
  6.   
  7.       };   

[java] view plain copy
print?
  1. class comparator1 implements Comparator  
  2. {  
  3.     public int compare(Object o1,Object o2)  
  4.     {  
  5.         return Integer.parseInt(o2.toString()) - Integer.parseInt(o1.toString());    
  6.     }  
  7. }  

第二步 初始化treemap时,构造函数中传入 该Comparator的实现类

[java] view plain copy
print?
  1. Map<String,Integer> map=new TreeMap<String,Integer>(comparator);  

这样,遍历treemap时 就是按照key的倒叙排列的了。

0 0
原创粉丝点击