Sorting and Duplicate Removal

The most basic sorting function is sort, which can sort by either the default comparator or a custom comparator if desired. For instance, this gets the first five planet names in alphabetical order:

 
(​take​ 5 (​sort​ (​map​ (:name planets))))

In this example, we’re retrieving the planet names, then sorting those names. Often, though, you want the original entities sorted by the planet’s name. That is, you want to sort by a function applied to each element rather than extracting the value. This can be accomplished with sort-by:

 
(​take​ 5 (​sort-by​ :name planets))

Both sort and sort-by require materialization of their outputs so don’t return lazy sequences. Neither has a transducer version.

To retrieve the smallest ...

Get Clojure Applied now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.