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

前端 未结 3 1194
旧巷少年郎
旧巷少年郎 2020-12-05 03:13

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

ArrayList

        
3条回答
  •  半阙折子戏
    2020-12-05 04:03

    You need to implement a Comparator> or more generally Comparator> 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>
    {
        private final String key;
    
        public MapComparator(String key)
        {
            this.key = key;
        }
    
        public int compare(Map first,
                           Map 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"));
    

提交回复
热议问题