Thursday, May 16, 2013

APEX Map sorting

I am programming in APEX from less than a month and I've already written those lines several times... so I think this may be useful for someone else coming to this point for the first time.

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.

2 comments:

  1. Sort this map

    theMap.put('Uiyt',5);
    theMap.put('jkiyt',10);
    theMap.put('sgd',1);
    theMap.put('ajsgdajs',1);
    theMap.put('sgd',9);

    ReplyDelete
  2. Thanks a lot, here I copy the (String, Integer) version.

    public static Map sortMap (Map theMap, String theOrder) {
    //create the return map
    Map returnMap = new Map();
    //get the set of the keys of the map we want to sort
    Set 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 keyList = new List();
    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;
    }

    ReplyDelete