对HashMap进行排序

1、使用Collections进行排序操作


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

map.put("d", 2);
map.put("c", 1);
map.put("b", 1);
map.put("a", 3);


List<Map.Entry<String, Integer>> infoIds =
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());


//排序前
for (int i = 0; i < infoIds.size(); i++) {
    String id = infoIds.get(i).toString();
    System.out.println(id);
}
//d 2
//c 1
//b 1
//a 3


//排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {   
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {      
        //return (o2.getValue() - o1.getValue()); 
        return (o1.getKey()).toString().compareTo(o2.getKey());
    }
}); 



//排序后
for (int i = 0; i < infoIds.size(); i++) {
    String id = infoIds.get(i).toString();
    System.out.println(id);
}
//根据key排序
//a 3
//b 1
//c 1
//d 2
//根据value排序
//a 3
//d 2
//b 1

//c 1


2、往TreeMap的构造函数传入一个比较器,来对map进行排序

class ValueComparator implements Comparator<String> {
    Map<String, Integer> base;


    public ValueComparator(Map<String, Integer> base) {
        this.base = base;
    }


    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }
}


public class Q12 {
    public static void printMap(Map mp) {
        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry) it.next();
            System.out.println(pairs.getKey() + " = " + pairs.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }
    }


    public static void main(String[] args) {
        HashMap<String, Integer> countMap = new HashMap<String, Integer>();
        // add a lot of entries
        countMap.put("a", 10);
        countMap.put("b", 20);
        ValueComparator vc = new ValueComparator(countMap);
        TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>(vc);
        sortedMap.putAll(countMap);
        printMap(sortedMap);


    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值