按照clojure中降序排列的键值对地图列表进行排序

时间:2016-07-08 12:52:13

标签: sorting clojure hashmap clojure-java-interop

我有一个目录大小为字符串的地图列表。我想按大小的降序排序: 问题是它包含单位,即GB或MB

列表如下所示:

    ({:directory_path /user/dod/1, :directory_size 8.49 MB} {:directory_path /user/dod/22, :directory_size 1.66 GB} {:directory_path /user/dod/testorc, :directory_size 1.28 MB} )

热来对它进行排序,使其按大小递减顺序?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

(defn str->float [s]
  (Float. s))

(defn filesize->num [fs]
  (let [[size unit] (clojure.string/split fs #" ")
        size (str->float size)]
    (condp = unit
          "MB" size
          "GB" (* size 1000))))

(def ->ds #(-> % :directory_size filesize->num))

(defn sort-data [data]
  (sort-by ->ds #(compare %2 %1) data))

(def data [{:directory_path "/user/dod/2", :directory_size "8.49 MB"}
           {:directory_path "/user/dod/22", :directory_size "1.66 GB"}
           {:directory_path "/user/dod/testorc", :directory_size "1.28 MB"}])

(sort-data data)