首页 > 其他 > 详细

SortedMap接口的实现类TreeMap介绍和实现Comparator自定义比较器(转)

时间:2017-01-01 00:05:12      阅读:210      评论:0      收藏:0      [点我收藏+]

与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
关键字: 

SortedMap接口的实现类TreeMap介绍和实现Comparator自定义比较器(转)

原文:http://www.cnblogs.com/Berryxiong/p/6240510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!