按值对 HashMap 进行排序 [英] Sorting HashMap by values

查看:55
本文介绍了按值对 HashMap 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据其中存储的值对我的 HashMap 进行排序.HashMap 包含存储在手机中的联系人姓名.

I need to sort my HashMap according to the values stored in it. The HashMap contains the contacts name stored in phone.

此外,我需要在对值进行排序后立即自动对键进行排序,或者您可以说键和值绑定在一起,因此值的任何更改都应反映在键中.

Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound together thus any changes in values should get reflected in keys.

HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"froyo");
map.put(2,"abby");
map.put(3,"denver");
map.put(4,"frost");
map.put(5,"daisy");

所需的输出:

2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;

推荐答案

假设使用 Java,您可以像这样对 hashmap 进行排序:

Assuming Java, you could sort hashmap just like this:

public LinkedHashMap<Integer, String> sortHashMapByValues(
        HashMap<Integer, String> passedMap) {
    List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
    List<String> mapValues = new ArrayList<>(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);

    LinkedHashMap<Integer, String> sortedMap =
        new LinkedHashMap<>();

    Iterator<String> valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
        String val = valueIt.next();
        Iterator<Integer> keyIt = mapKeys.iterator();

        while (keyIt.hasNext()) {
            Integer key = keyIt.next();
            String comp1 = passedMap.get(key);
            String comp2 = val;

            if (comp1.equals(comp2)) {
                keyIt.remove();
                sortedMap.put(key, val);
                break;
            }
        }
    }
    return sortedMap;
}

只是一个启动示例.这种方式更有用,因为它可以对 HashMap 进行排序并保留重复值.

Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.

这篇关于按值对 HashMap 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆