android treemap put的时候是不是会排序,TreeMap 对Key和Value升序|降序排列

TreeMap 升序|降序排列

import java.util.Comparator;import java.util.TreeMap;publicclass Main {

publicstaticvoid main(String[] args) {

TreeMap map1 =newTreeMap();//默认的TreeMap升序排列TreeMap map2=newTreeMap(newComparator(){

/*

* int compare(Object o1, Object o2) 返回一个基本类型的整型,

* 返回负数表示:o1 小于o2,

* 返回0 表示:o1和o2相等,

* 返回正数表示:o1大于o2。

*/publicint compare(Integer a,Integer b){

returnb-a;

}

});

map2.put(1,2);

map2.put(2,4);

map2.put(7, 1);

map2.put(5,2);

System.out.println("Map2="+map2);

map1.put(1,2);

map1.put(2,4);

map1.put(7, 1);

map1.put(5,2);

System.out.println("map1="+map1);

}

}

TreeMap按照value进行排序

TreeMap底层是根据红黑树的数据结构构建的,默认是根据key的自然排序来组织(比如integer的大小,String的字典排序)。所以,TreeMap只能根据key来排序,是不能根据value来排序的(否则key来排序根本就不能形成TreeMap)。

今天有个需求,就是要根据treeMap中的value排序。所以网上看了一下,大致的思路是把TreeMap的EntrySet转换成list,然后使用Collections.sor排序。代码:

publicstaticvoid sortByValue() {

Map map =newTreeMap();

map.put("a", "dddd");

map.put("d", "aaaa");

map.put("b", "cccc");

map.put("c", "bbbb");

List> list =newArrayList>(map.entrySet());

Collections.sort(list,newComparator>() {

//升序排序publicintcompare(Entry o1, Entry o2) {

return o1.getValue().compareTo(o2.getValue());

}

});

for(Entry e: list) {

System.out.println(e.getKey()+":"+e.getValue());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值