与SortedSet接口类似,SortedMap也是一个结构,待排序的Map,其一个比较常用的实现类是TreeMap。

TreeMap的put(K key, V value)方法在每添加一个元素时,都会自动排序。

构造方法:
TreeMap()
使用键的自然顺序构造一个新的、空的树映射。
TreeMap(Comparator<? super K> comparator)
构造一个新的、空的树映射,该映射根据给定比较器进行排序。
TreeMap(Map<? extends K,? extends V> m)
构造一个与给定映射具有相同映射关系的新的树映射,该映射根据其键的自然顺序 进行排序。

创建自定义的Comparator比较器:

//这里根据字符的ASCII码大小进行降序排序:
class MyComparator2 implements Comparator<String>{
@Override
public int compare(String o1, String o2) { return o2.compareTo(o1);
}
}

在SortedSet中,当保存对象时一定要自定义一个比较器Comparator,但是在SortedMap中,保存对象却不一定要,因为 SortedMap是比较Key而不是Value,所以创建的自定义比较器也是针对Key的,比如上面创建的Comparator是针对Key类型为 String的Map进行排序。

Map<String, String> map = new TreeMap<String, String>(new MyComparator2());

对于TreeMap的迭代和HashMap一样,同样有三种方法,以下是常用的其中一种:

Set<Map.Entry<Integer, Integer>> set = map.entrySet();
for(Iterator<Map.Entry<Integer, Integer>> iter = set.iterator(); iter.hasNext();){
Map.Entry<Integer, Integer> entry = iter.next();
Integer key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ":" + value);
}

对于Map来说,不能使用Collections的静态方法,但是可以通过他的values方法获取到Collections进行调用:

Collection<Integer> cols = map.values();
Integer max = Collections.max(cols);
除了文章中有特别说明,均为IT宅原创文章,转载请以链接形式注明出处。
本文链接:http://www.itzhai.com/treemap-sortedmap-interface-implementation-class-introduction-and-implementation-of-custom-comparator-comparator.html
关键字: ComparatorJavaSortedMapTreeMap

最新文章

  1. Codeforces Round #341 Div.2 D. Rat Kwesh and Cheese
  2. yii2权限控制rbac之rule详细讲解(转)
  3. IOS-Uikit框架介绍
  4. 20145215实验五 Java网络编程及安全
  5. 杭电HDU1042(有点坑的高精度)
  6. linux基础--chkconfig 详解
  7. TimeDelta.total_seconds() in Python2.6-
  8. Django-Views模块详解
  9. 51nod_1412_AVL树的种类_动态规划
  10. 【转】C语言堆栈入门——堆和栈的区别
  11. MySQL数据性能优化-修改方法与步骤
  12. 【资料下载区】【GK101固件】更新日期2017/1/11
  13. (9/24) 图片跳坑大战--css分离与图片路径处理
  14. T-SQL编程中的异常处理-异常捕获(try catch)与抛出异常(throw)
  15. testNG 学习笔记 Day 3 常用的断言
  16. Oracle 起诉 Google 事件
  17. Ubuntu 18.04安装MongoDB 4.0(社区版)
  18. tcp协议的端口状态
  19. enmu枚举类型
  20. 封装boto3 api用于服务器端与AWS S3交互

热门文章

  1. [No00005D]如何高效利用GitHub
  2. css的小问题总结
  3. Android开篇(转)
  4. Clock Skew , Clock Uncertainty和 Period
  5. MySQL for mac使用记录
  6. Codeforces Round #358(div 2)
  7. JS 页面加载触发事件 document.ready和window.onload的区别
  8. go println与printf区别
  9. nginx location语法使用说明
  10. C++ vector用法