We have a map, whose key may be Integer, String or whatever else is a Primitive type. We want to sort it, in ascending or descending order.
Here's a quick method:
public Map<Key_object, Value_object> sortMap (Map<Key_object, Value_object> theMap, String theOrder) { //create the return map Map<Key_object, Value_object> returnMap = new Map<Key_object, Value_object>(); //get the set of the keys of the map we want to sort Set<Key_object> keySet = theMap.keySet(); //create a list and add all the keys from the set //a small workaround needed because we can't sort a set List<Key_object> keyList = new List<Key_object>(); keyList.addAll(keySet); //sort the list ascending (predefined behaviour) keyList.sort(); if (theOrder == 'DESC') //iterate from the last to the first key over the ascending ordered key list for (Integer i = (keyList.size() - 1); i >= 0; i--) returnMap.put(keyList[i], theMap.get(keyList[i])); else //iterate from the first to the last key over the ascending ordered key list for (Integer i = 0; i < keyList.size(); i++) returnMap.put(keyList[i], theMap.get(keyList[i])); //return the sorted map return returnMap; }
Of course we can omit the part regarding the order (if we want only ascending or descending order) or create two different methods for this.