If this is the best (or a good) solution, can someone please explain exactly what it’s doing?
(sort
(reduce (fn [x [y z]] (assoc x y z)) {} (System/getProperties)))
Where it can be used, for example to print the System properties:
(def p
(sort
(reduce (fn [x [y z]] (assoc x y z)) {} (System/getProperties))))
(defn pnv [nv] (println (str (key nv) "=\"" (val nv) "\"")))
(doseq [nv p] (pnv nv))
If that isn’t a good approach, please provide a better one. Thanks
I know that i can do:
(doseq [nv (System/getProperties)] (pnv nv))
But sorting doesn’t seem to work:
(doseq [nv (sort (System/getProperties))] (pnv nv))
ClassCastException java.util.Hashtable$Entry cannot be cast to java.lang.Comparable clojure.lang.Util.compare (Util.java:104)
Solution, as provided by amalloy:
(doseq [nv (into (sorted-map) (System/getProperties))] (pnv nv))
Maps are in general not sorted – certainly any map you get to by adding entries to
{}won’t be. However, both Clojure and Java provide sorted maps. So if you want a sorted map with the default sort order, you can just do(into (sorted-map) the-other-map). This works for java.util.Map as well as for Clojure types, so it should be all you need.