简体   繁体   English

如何在Clojure中映射PersistentHashMaps的PersistentVector?

[英]How to map PersistentVector of PersistentHashMaps in Clojure?

I have a PersistentVector of PersistentHashMaps: 我有一个PersistentHashMaps的PersistentVector:

[
  {:url http://www.url.com, id: some_id ...},
  {:url http://www.url.com, id: some_id ...},
  {:url http://www.url.com, id: some_id ...},
]

What I need here to have a collection of all id s, so I need to map over a vector and from each map select id value. 我在这里需要具有所有id的集合,因此我需要映射一个向量,并从每个映射中选择id值。

I do: 我做:

(map #(get % :id) (all-users))

Is there a better way to do this? 有一个更好的方法吗?

Keywords can be used as functions. 关键字可用作功能。

(map :id (all-users))

If you are on Clojure 1.7 and don't need laziness, eg want to realize they entire collection as a vector you can use the map transducer: 如果您使用的是Clojure 1.7,并且不需要懒惰,例如想要将它们的整个集合作为矢量实现,则可以使用地图转换器:

(into [] (map :id) (all-users))

Unless you know that you need the lazy behavior of map, I would always suggest using mapv : 除非您知道需要map的惰性行为,否则我总是建议您使用mapv

(def all-users [ {:id 111 ...} 
                 {:id 222 ...}
                 ... ] )
(mapv :id all-users)

The difference is that mapv is always evaluated immediately, and it stuffs the results in to a vector for easy access. 不同之处在于,始终会立即评估mapv ,并将结果mapv到向量中以便于访问。 Lazy sequences are great for things that are either very large or very slow, but they introduces an added layer of timing uncertainty that is unneeded by 99% of use cases. 延迟序列非常适合非常大或非常慢的事物,但是它们引入了时序不确定性的附加层,而用例的99%则不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM