- Clojure - Libraries
- Clojure - Automated Testing
- Clojure - Applications
- Clojure - Concurrent Programming
- Clojure - Java Interface
- Clojure - Databases
- Clojure - Reference Values
- Clojure - Macros
- Clojure - Watchers
- Clojure - Agents
- Clojure - StructMaps
- Clojure - Metadata
- Clojure - Atoms
- Clojure - Date & Time
- Clojure - Destructuring
- Clojure - Predicates
- Clojure - Regular Expressions
- Clojure - Sequences
- Clojure - Exception Handling
- Clojure - Namespaces
- Clojure - Maps
- Clojure - Vectors
- Clojure - Sets
- Clojure - Lists
- Clojure - Strings
- Clojure - File I/O
- Clojure - Recursion
- Clojure - Numbers
- Clojure - Functions
- Clojure - Decision Making
- Clojure - Loops
- Clojure - Operators
- Clojure - Variables
- Clojure - Data Types
- Clojure - REPL
- Clojure - Basic Syntax
- Clojure - Environment
- Clojure - Overview
- Clojure - Home
Clojure Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Clojure - Maps
A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator.
A map can be created in two ways, the first is via the hash-map method.
Creation - HashMaps
HashMaps have a typical key value relationship and is created by using hash-map function.
(ns clojure.examples.example (:gen-class)) (defn example [] (def demokeys (hash-map "z" "1" "b" "2" "a" "3")) (println demokeys)) (example)
Output
The above code produces the following output.
{z 1, b 2, a 3}
Creation - SortedMaps
SortedMaps have the unique characteristic of sorting their elements based on the key element. Following is an example that shows how the sorted map can be created using the sorted-map function.
(ns clojure.examples.example (:gen-class)) (defn example [] (def demokeys (sorted-map "z" "1" "b" "2" "a" "3")) (println demokeys)) (example)
The above code produces the following output.
{a 3, b 2, z 1}
From the above program you can clearly see that elements in the maps are sorted as per the key value. Following are the methods available for maps.
Sr.No. | Maps & Description |
---|---|
1 | Returns the value mapped to key, not-found or nil if key is not present. |
2 | See whether the map contains a required key. |
3 | Returns the map entry for the key. |
4 | Returns the pst of keys in the map. |
5 | Returns the pst of values in the map. |
6 | Dissociates a key value entry from the map. |
7 | Merges two maps entries into one single map entry. |
8 | Returns a map that consists of the rest of the maps conj-ed onto the first. |
9 | Returns a map containing only those entries in map whose key is in keys. |
10 | Renames keys in the current HashMap to the newly defined ones. |
11 | Inverts the maps so that the values become the keys and vice versa. |