DEV Community

Cover image for Exploring Clojure: HashMap 🤠🔍
Marcos Henrique
Marcos Henrique

Posted on

Exploring Clojure: HashMap 🤠🔍

How is it working?

Like a dictionary ... Basically, a HashMap allows you to store items with identifiers.
They are stored in a table format with the identifier being hashed using a hashing algorithm.
Typically they are more efficient to retrieve items than search trees etc..
It's commom represented by {key:value} syntax.

A HashMap is a collection that maps keys to values. They have various names in other languages; Python refers to them as dictionaries, and JavaScript’s objects essentially work like hashmaps.

You can see more about HashMap here.

How I can use this on Clojure?

Clojure works with a syntax where we first define what we are going to do, that is, the action and then what we want to pass to it, very similar to the mathematical functions.

So we have two ways to define a HashMap, for this let's assume we have a stock of which we have 2 backpacks and a t-shirt.

Dumb way


(def store {"backpack" 2 "t-shirt" 1})
(println "We have" store)
Enter fullscreen mode Exit fullscreen mode

This way isn't the best because it's implements a string as key, the most correctly is the use of keyword, let's see how we use in Clojure.

The correctly way


(def store {:backpack 10 :t-shirt 5})
(println "We have" store)
Enter fullscreen mode Exit fullscreen mode

Why I need keyword? Well, unlike strings, keywords can be used as functions to extract values from a hashmap no need for get or nth !

Using only string will retrieve to us an exception when we try to access like example above

("backpack" store)
Enter fullscreen mode Exit fullscreen mode

This returns an ClassCastException java.lang.String cannot be cast to clojure.lang.IFn

But when we use the correctly way returns to us exactly value of keyword we access

(:backpack store)
;returns 2
Enter fullscreen mode Exit fullscreen mode

Bonus track 🎉🎊

Handling hashmaps

In Clojure symbols like array, hashmaps, etc... are immutable, so when we handle a value then return to us a clone of the symbol with a modified value

Assoc (adding a :key and value)

(def store {:backpack 10 :t-shirt 5})
(println (assoc store :pen 2)
;returns {:backpack 10 :t-shirt 5 :pen 2}
Enter fullscreen mode Exit fullscreen mode

Dissoc (remove a :key)

(def store {:backpack 10 :t-shirt 5})
(println (dissoc store :t-shirt)
;returns {:backpack 10}
Enter fullscreen mode Exit fullscreen mode

Update (using a function to update our hashmap)

(def store {:backpack 10 :t-shirt 5})
(println (update store :backpack inc))
;retunrs {:backpack 10 :t-shirt 6}
Enter fullscreen mode Exit fullscreen mode

Just for today, anything from hello in the comments to discuss this wonderful language 🍻

Top comments (0)