Sorting Lists that Contain Maps in Deluge (Flexible, Field-Based Sort)

Mon Jan 20 2025
Deluge · Collections

Sorting Lists that Contain Maps in Deluge

A list of maps is like a small table: keys are columns, values are cells. Deluge doesn’t have a native “sort by key” for a list of maps, so here’s a reliable pattern that sorts by any key (string, number, or date) without altering your data.

Mostafa Badawy··~5 min read

Sample dataset (copy/paste for testing)

[
  {"Item":"Orange","Sold_On":"2020-04-18","Units":20},
  {"Item":"Apple","Sold_On":"2020-02-28","Units":15},
  {"Item":"Kiwi","Sold_On":"2020-05-15","Units":50},
  {"Item":"Peach","Sold_On":"2020-11-22","Units":35},
  {"Item":"Strawberry","Sold_On":"2020-12-24","Units":10},
  {"Item":"Watermelon","Sold_On":"2021-01-11","Units":25}
]

The sorting pattern (rename-friendly, works as-is)

Configure fieldToSort to any key that exists in your maps. The code builds a list of that field’s values, sorts it, then walks the original list in the order of the sorted values to produce a new, sorted list.

// ===== Deluge: sort a List<Map> by any key =====

// Your original list of maps:
sourceRows = [
  {"Item":"Orange","Sold_On":"2020-04-18","Units":20},
  {"Item":"Apple","Sold_On":"2020-02-28","Units":15},
  {"Item":"Kiwi","Sold_On":"2020-05-15","Units":50},
  {"Item":"Peach","Sold_On":"2020-11-22","Units":35},
  {"Item":"Strawberry","Sold_On":"2020-12-24","Units":10},
  {"Item":"Watermelon","Sold_On":"2021-01-11","Units":25}
];

// 1) Choose the field/key to sort by (change this to "Item" or "Sold_On" as needed)
fieldToSort = "Units";

// 2) Collect values of that key so we can sort them
fieldValues = List();
for each r in sourceRows
{
  fieldValues.add(r.get(fieldToSort));
}

// 3) Sort the values to define the desired order
//    true  = ascending (default)
//    false = descending
fieldValues = fieldValues.distinct().sort(true);

// 4) Build the final sorted list by following the sorted values
sortedRows = list();
for each v in fieldValues
{
  for each r in sourceRows
  {
    if (r.get(fieldToSort) == v)
    {
      sortedRows.add(r);
    }
  }
}

// Inspect results
info "Sorted by " + fieldToSort + " (asc):";
info sortedRows;

Descending order

// Just change the flag in step 3:
fieldValues = fieldValues.distinct().sort(false); // descending
// The rest stays the same

Sorting by a different key

Swap fieldToSort to "Item" or "Sold_On" without changing the rest of the code. Because the pattern reuses the same logic, you avoid repeated copy/paste functions for each field.

Notes: If your source contains duplicate values for the sort field, this approach keeps the original row order within each value group. If you need a secondary sort, run the pattern again on the result with another field.