You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Clojure中统计数组内的Map数量?附示例验证

How to Count the Number of Maps in a Clojure Collection?

Hey there! Let's break down how to solve this problem with your example in mind.

First, let's recall your sample input: [{:a "a"} {:b "b"}] — you want to get the count of Map entries here, which should be 2.

Method 1: Filter + Count

The most straightforward approach is to use filter to keep only elements that are Maps, then use count to tally them up. Clojure has a built-in predicate map? that checks if an element is a Map type.

Here's the code:

(count (filter map? [{:a "a"} {:b "b"}]))

When you run this, it'll return 2 exactly as you expected. Let's break it down:

  • map? checks each element in the collection to see if it's a Map
  • filter creates a new sequence containing only elements where map? returns true
  • count then counts how many elements are in that filtered sequence

Method 2: Reduce for Manual Accumulation

If you prefer a more explicit approach, you can use reduce to iterate through the collection and increment a counter each time you encounter a Map:

(reduce (fn [acc elem] (if (map? elem) (inc acc) acc)) 0 [{:a "a"} {:b "b"}])

This works by initializing the counter (acc) to 0, then for each element:

  • If it's a Map, increment the counter
  • Otherwise, keep the counter the same
    At the end, you'll have the total count of Maps.

Bonus: Handling Mixed Collections

Both methods work even if your collection has other types of elements. For example, if you have [{:a 1} "test" 42 {:b 2}], running either of the above code snippets will return 2, correctly ignoring the string and number.

内容的提问来源于stack exchange,提问作者THX1137

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:28:48