sorted-set-by constructs an ordered set from a comparator followed by any number of keys. Iteration follows comparator order, while duplicate keys are omitted. section 13.3
Use the constructor with these practical rules:
- Pass any object implementing java.util.Comparator; ordinary Clojure comparison functions such as <, >, >=, and <= can serve as comparators. section 13.3
- Expect a PersistentTreeSet containing distinct keys; iteration uses the supplied comparator rather than the default ordering. section 13.3
- Avoid incomparable key pairs, which can raise ClassCastException; different numeric types remain comparable. section 13.3
Reverse order and comparator ties
(sorted-set-by #(compare %2 %1) "t" "d" "j" "w" "y") ;; #{"y" "w" "t" "j" "d"} ;; A comparator that compares only lengths drops equal-length values: (sorted-set-by (fn [a b] (compare (count b) (count a))) [1 :a] [:b] [3 :c] [:v]) ;; #{[1 :a] [:b]} ;; Add a tie-breaker when equal lengths must remain distinct.
