📅  最后修改于: 2020-11-05 04:02:00             🧑  作者: Mango
映射是将键映射到值的集合。提供了两种不同的地图类型-哈希和排序。 HashMaps需要正确支持hashCode和equals的键。 SortedMaps需要实现Comparable的键或Comparator的实例。
可以通过两种方式创建映射,第一种是通过hash-map方法。
HashMap具有典型的键值关系,并且是通过使用hash-map函数创建的。
(ns clojure.examples.example
(:gen-class))
(defn example []
(def demokeys (hash-map "z" "1" "b" "2" "a" "3"))
(println demokeys))
(example)
上面的代码产生以下输出。
{z 1, b 2, a 3}
SortedMaps具有基于key元素对其元素进行排序的独特特征。以下示例显示了如何使用sorted-map函数创建排序后的地图。
(ns clojure.examples.example
(:gen-class))
(defn example []
(def demokeys (sorted-map "z" "1" "b" "2" "a" "3"))
(println demokeys))
(example)
上面的代码产生以下输出。
{a 3, b 2, z 1}
从上面的程序中,您可以清楚地看到映射中的元素是根据键值排序的。以下是可用于地图的方法。
Sr.No. | Maps & Description |
---|---|
1 | get
Returns the value mapped to key, not-found or nil if key is not present. |
2 | contains?
See whether the map contains a required key. |
3 | find
Returns the map entry for the key. |
4 | keys
Returns the list of keys in the map. |
5 | vals
Returns the list of values in the map. |
6 | dissoc
Dissociates a key value entry from the map. |
7 | merge
Merges two maps entries into one single map entry. |
8 | merge-with
Returns a map that consists of the rest of the maps conj-ed onto the first. |
9 | select-keys
Returns a map containing only those entries in map whose key is in keys. |
10 | rename-keys
Renames keys in the current HashMap to the newly defined ones. |
11 | map-invert
Inverts the maps so that the values become the keys and vice versa. |