Java: Sort a HashMap by its Value

When you use a TreeMap, the entries in the Map is sorted by the keys. 

 

This following code outputs the elements of the map sorted by value. 

import java.util.*;

@SuppressWarnings("unchecked") // for JDK 1.5 and above
public class HashMapSort {
    public static void main(String[] args) {
        Map m = new HashMap();
        m.put("a", "some");
        m.put("b", "random");
        m.put("c", "words");
        m.put("d", "to");
        m.put("e", "be");
        m.put("f", "sorted");
        m.put("g", "by");
        m.put("h", "value");
        for (Iterator i = sortByValue(m).iterator(); i.hasNext(); ) {
            String key = (String) i.next();
            System.out.printf("key: %s, value: %s\n", key, m.get(key));
        }
    }

    public static List sortByValue(final Map m) {
        List keys = new ArrayList();
        keys.addAll(m.keySet());
        Collections.sort(keys, new Comparator() {
            public int compare(Object o1, Object o2) {
                Object v1 = m.get(o1);
                Object v2 = m.get(o2);
                if (v1 == null) {
                    return (v2 == null) ? 0 : 1;
                }
                else if (v1 instanceof Comparable) {
                    return ((Comparable) v1).compareTo(v2);
                }
                else {
                    return 0;
                }
            }
        });
        return keys;
    }
}
 
The output is: 

key: e, value: be
key: g, value: by
key: b, value: random
key: a, value: some
key: f, value: sorted
key: d, value: to
key: h, value: value
key: c, value: words
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值