Logo

Programming-Idioms

  • Erlang
  • Groovy

Idiom #28 Sort by a property

Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.

items.sort { x, y -> x.p <=> y.p }

Sort using the spaceship operator
items.sort { x -> x.p }
	
sort_by_birth(ListOfMaps) ->
  lists:sort(
    fun(A, B) ->
      maps:get(birth, A, undefined) =< maps:get(birth, B, undefined)
    end, ListOfMaps).

sort_by_birth(ListOfRecords) -> lists:keysort(#item.birth, ListOfRecords).

First function works with a list of maps, like [#{birth => "1982-01-03"}, …].
Second function works with a list of records, like [#item{birth = "1982-01-03", …}, …]
with Ada.Containers.Vectors;
use Ada.Containers;
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;

New implementation...
< >
programming-idioms.org