TreeMap的使用和了解

TreeMap 基于红黑树实现,该映射根据键值(key-value集合)的自然顺序进行排序(默认排序),默认是按升序排序;

TreeMap是Map接口的集合类,也具备了Map接口的特点:存储数据都是以键值对的形式存在,键不可重复,值可以重复;

  1. 它实现Serializable接口,意味着它可以被系列化;
  2. 由于TreeMap是有序的,也支持Comparable和Comparator两种排序方式。

下面看一下如何使用treeMap:

最简单的使用方法了,创建一个TreeMap集合,往集合添加键值对;如何取值?

    它不可以像list集合一样直接通过遍历获取;键值对的结构使它和其他的集合取值方法有点不一样,先把TreeMap所有键获取到,然后通过键获取其对应的值;

运行结果:

    可以看到它是已经排序好的,说明它自身有排序的方式;

下面看一下如何自定义的进行Comparator排序:

    直接new 一个比较接口进行排序;

运行结果:

控制排序方式:

return o2.charAt(0)-o1.charAt(0);  ---降序

return o1.charAt(0)-o2.charAt(0);  ---升序

排序代码:

//TreeMap排序,使用Comparator比较接口实现排序
      TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(new Comparator<String>() {

				@Override
				public int compare(String o1, String o2) {
			
					if (o1==null) {
						return 1;
					}else {
						return o2.charAt(0)-o1.charAt(0);
					}
				}
			});
		     treeMap.put("2",4);
		     treeMap.put("1",3);
		     treeMap.put("2",1);
		     treeMap.put("5",10);
		     treeMap.put("6",4);
		     treeMap.put("4",3);
		     treeMap.put("3",1);
		     treeMap.put("99",10);
		     //用遍历形式都可以获取值
		     for(Entry<String, Integer> entry:treeMap.entrySet()){
		         System.out.println("key:"+entry.getKey()+" --value:"+entry.getValue());
		     }

TreeMap方法:

执行方法:

TreeMap<Integer, String> map = new TreeMap<>();
// 添加数据 put当key不存在时,添加key‐value
map.put(1, "str1");
map.put(2, "str2");
map.put(3, "str3");
map.put(4, "str4");
map.put(5, "str5");
// put 当key存在时,修改key对应的value
map.put(5, "111111");
map.put(6, null);
map.put(7, null);
System.out.println(map);
System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
//firstEntry() firstKey() lastEntry() lastKey()
System.out.println("firstEntry()‐‐‐>"+map.firstEntry());
System.out.println("firstKey()‐‐‐>"+map.firstKey());
System.out.println("lastEntry()‐‐‐>"+map.lastEntry());
System.out.println("lastKey()‐‐‐>"+map.lastKey());
System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
//higherEntry(K key) higherKey(K key) lowerEntry(K key) lowerKey(K key)
System.out.println("higherKey(4)‐‐‐>"+map.higherKey(4));
System.out.println("higherEntry(4)‐‐‐>"+map.higherEntry(4));
System.out.println("lowerKey(4)‐‐‐>"+map.lowerKey(4));
System.out.println("lowerEntry(4)‐‐‐>"+map.lowerEntry(4));
System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
// headMap(K toKey) tailMap(K fromKey) subMap(K fromKey, K toKey)
Map<Integer,String> mapHeadMap=map.headMap(4);
Map<Integer,String> mapTailMap=map.tailMap(4);
Map<Integer,String> mapSubMap=map.subMap(2,5);
System.out.println("headMap(4)‐‐‐>"+mapHeadMap);
System.out.println("tailMap(4)‐‐‐>"+mapTailMap);
System.out.println("subMap(2,5)‐‐‐>"+mapSubMap);

运行结果:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值