Java Joyless
27 January 2021
Mr Haki has a Java Joy article about transforming a stream of strings into a map using functional Java. I’m having a bit of trouble embracing it enthusiastically, since each example is 81 lines of Java code and a pointy pile of type declarations!
I dashed out the same functionality in 4 lines of Clojure, and I can understand it a whole lot easier. I’m not even sure this is the fewest forms, but it’s still nicer.
(->> ["language" "clojure" "username" "john"] (partition 2) (reduce (fn [m [k v]] (assoc m k v)) {})) ;; => {"language" "clojure", "username" "john"}
Update 2021-04-14: It can be done in one line of Clojure.
(apply hash-map ["language" "clojure" "username" "john"]) ;; => {"language" "clojure", "username" "john"}
Written with Clojure 1.10.2.