Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use sorted-map-by to sort a map by value?

Tags:

clojure

I cant understand the documentation at all.

I want a sorted map "xxx", which sorts the map according to the value. How do I do that?

Thanks.

like image 790
unj2 Avatar asked Oct 06 '09 23:10

unj2


People also ask

How do you sort a map using values?

Example: Sort a map by values Inside the method, we first created a list named capitalList from the map capitals . We then use the sort() method of Collections to sort elements of the list. The sort() method takes two parameters: list to be sorted and a comparator. In our case, the comparator is a lambda expression.

Is map sorted by key or value?

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key.

How do I sort things on a map?

Sort HashMap by Values using Comparator Interface After that get the Set of elements from the Map and convert Set into the List. Use the Collections. sort(List) method to sort the list of elements by values by passing customized comparator. Now create a new LinkedHashMap and copy the sorted elements into that.

Can we sort map in C++ by value?

Sorting of Map by valueCopy all contents from the map to the corresponding vector of pairs and sort the vector of pairs according to second value using the lambda function. Multimap is a map with an addition that multiple elements can have the same keys.


2 Answers

Another way is to compare the values from the original map within the comparer function.

(def my-map {:chad 3 :bob 5 :sammy 4})

;; sort by keys ascending
(into (sorted-map) my-map)
=> {:bob 5, :chad 3, :sammy 4}

;; sort by values ascending
(into (sorted-map-by (fn [key1 key2] (compare (key1 my-map) (key2 my-map)))) my-map)
=> {:chad 3, :sammy 4,  :bob 5}

;; sort by values descending
(into (sorted-map-by (fn [key1 key2] (compare (key2 my-map) (key1 my-map)))) my-map)
=> {:bob 5, :sammy 4, :chad 3}
like image 123
Chad Braun-Duin Avatar answered Nov 03 '22 01:11

Chad Braun-Duin


You use sorted-map-by by specifying a comparisson followed by the key-value-pairs. The comparator is a function which takes two keys and returns -1, 0 or 1 depending on whether the first key is smaller than, equal to or greater than the second key.

Example:

user=> (sorted-map-by (fn [k1 k2] (compare (mod k1 10) (mod k2 10))) 10 1 23 4 2 5)
{10 1, 2 5, 23 4}

Since the comparisson function only takes keys as arguments, you can't use this to sort by the values.

There is no way to have a sorted map where the map is sorted by the values. If it were, it wouldn't be possible to find an entry by key because you could not use the order to determine where the entry is (since the order would not depend on the key).

like image 41
sepp2k Avatar answered Nov 03 '22 01:11

sepp2k