Adam Sznajder
Adam Sznajder

Reputation: 9206

How to iterate over TreeMap in Clojure?

I use Clojure 1.1.0 and I want to iterate over all elements of TreeMap. How can I do this?

Upvotes: 1

Views: 885

Answers (2)

Matt Fenwick
Matt Fenwick

Reputation: 49085

Additionally, you can also use the map function and list comprehensions via the for macro to process every entry in a java.util.TreeMap:

> (def t (new java.util.TreeMap {:a 1 :b 2}))

;; reverse all the pairs
> (map (fn [e] [(val e) (key e)]) t)
([1 :a] [2 :b])

;; same thing, but with destructuring/for
> (for [[k v] t] 
       [v k])
([1 :a] [2 :b])

Upvotes: 4

soulcheck
soulcheck

Reputation: 36767

You could do it by using seq/doseq just like with normal clojure maps

(doseq [entry treeMap] (
    prn (key entry) (val entry))
)

where treeMap is your TreeMap instance.

Upvotes: 3

Related Questions