map 排序

TreeMap 和 HashMap 用法大致相同,但实际需求中,我们需要把一些数据进行排序;
以前在项目中,从数据库查询出来的数据放在List中,顺序都还是对的,但放在HashMap中,顺序就完全乱了。

为了处理排序的问题:
1. 对于一些简单的排序,如:数字,英文字母等
TreeMap hm = new TreeMap<String, String>(new Comparator() {
public int compare(Object o1, Object o2) {
//如果有空值,直接返回0
if (o1 == null || o2 == null)
return 0;

return String.valueOf(o1).compareTo(String.valueOf(o2));
}
});
备注:
compareTo(String str) :是String 提供的一个方法,如果参数字符串等于此字符串,
则返回 0 值;如果按字典顺序此字符串小于字符串参数,则返回一个小于 0 的值;
如果按字典顺序此字符串大于字符串参数,则返回一个大于 0 的值。

int compare(T o1,T o2):随第一个参数小于、等于或大于第二个参数而分别返回负整数、
零或正整数。


2.对于处理有中文排序的问题
TreeMap hm = new TreeMap<String, String>(new Comparator() {
public int compare(Object o1, Object o2) {
//如果有空值,直接返回0
if (o1 == null || o2 == null)
return 0;
Collator collator = Collator.getInstance();
CollationKey ck1 = collator.getCollationKey(String.valueOf(o1));
CollationKey ck2 = collator.getCollationKey(String.valueOf(o2));
return ck1.compareTo(ck2);
}
});

备注: CollationKey:CollationKey 表示遵守特定 Collator 对象规则的 String。
比较两个CollationKey 将返回它们所表示的 String 的相对顺序。使用 CollationKey
来比较 String 通常比使用 Collator.compare 更快。因此,当必须多次比较 String 时
(例如,对一个 String 列表进行排序),使用 CollationKey 会更高效。

根据Value排序

Map<String, Integer> keyfreqs = new HashMap<String, Integer>();

ArrayList<Entry<String,Integer>> l = new ArrayList<Entry<String,Integer>>(keyfreqs.entrySet());

Collections.sort(l, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});

for(Entry<String,Integer> e : l) {
System.out.println(e.getKey() + "::::" + e.getValue());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值