简体   繁体   中英

How sort an ArrayList of HashMaps holding several key-value pairs each?

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);
    }

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

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"));

您可以使用以下解决方案来实现它:

arrayListHashMap.sort(Comparator.comparing(m -> m.get("value"), Comparator.nullsLast(Comparator.naturalOrder())));

(This is not an answer to the asked question - Jon did this already -, but the comment field is too small for this.)

Your data structure looks like you misunderstood the key-value structure of maps (and Hash maps in your example).

A Map can contain any number of keys, and for each key also a value. A pair of key and value is given by a Map.Entry (which can be obtained by the entrySet() method of the map). If you then want to sort by key, simply use a SortedMap (like TreeMap) instead of the usual HashMap.

You are emulating the individual entries by a HashMap each, then putting them all in a ArrayList ... :-/

Here what I would have done in your example:

Map<String, String> map = new TreeMap<String, String>();
map.put("B key", "B value");
map.put("A key", "B value");

System.out.println(map); // already sorted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM