Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...