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.
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.
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.
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.
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.
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}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With