如何对HashMaps的ArrayList排序,每个ArrayList包含几个键值对? [英] How sort an ArrayList of HashMaps holding several key-value pairs each?

查看:110
本文介绍了如何对HashMaps的ArrayList排序,每个ArrayList包含几个键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用HashMaps的ArrayList调用外部API,每个ArrayList包含多个预定义的键值对.一个例子:

I need to call an external API with an ArrayList of HashMaps holding several predefined key-value pairs each. An example:

ArrayList<HashMap<String, String>> arrayListHashMap = new ArrayList<HashMap<String, String>>();

    {
        HashMap hashMap = new HashMap<String, String>();
        hashMap.put("key", "A key");
        hashMap.put("value", "B value");
        arrayListHashMap.add(hashMap);
    }

    {
        HashMap hashMap = new HashMap<String, String>();
        hashMap.put("key", "B key");
        hashMap.put("value", "A value");
        arrayListHashMap.add(hashMap);
    }

现在,我需要根据值"键的内容对该结构进行排序.这种排序将导致"key = B键/值= A值"条目作为arrayListHashMap中的第一个条目.

Now I need to sort this construct on the contents of the "value" key. This sort would result in the "key=B key/value=A value" entry as the first one in the arrayListHashMap.

我们非常感谢您的帮助.

Any help is highly appreciated.

HJW

推荐答案

您需要实现一个Comparator<HashMap<String, String>>或更一般的Comparator<Map<String, String>>,它只提取与value键关联的值,然后使用Collections.sort.示例代码(对要排序的任何键进行泛化):

You need to implement a Comparator<HashMap<String, String>> or more generally Comparator<Map<String, String>> which just extracts the value assocated with the value key, then use Collections.sort. Sample code (with generalization for whatever key you want to sort on):

class MapComparator implements Comparator<Map<String, String>>
{
    private final String key;

    public MapComparator(String key)
    {
        this.key = key;
    }

    public int compare(Map<String, String> first,
                       Map<String, String> second)
    {
        // TODO: Null checking, both for maps and values
        String firstValue = first.get(key);
        String secondValue = second.get(key);
        return firstValue.compareTo(secondValue);
    }
}

...
Collections.sort(arrayListHashMap, new MapComparator("value"));

这篇关于如何对HashMaps的ArrayList排序,每个ArrayList包含几个键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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