What is the contains method of the map in Clojure?

Overview

A map is a collection that assigns keys to values.

A contains method is used to search for a key in a collection. It is used to check if a key exists in a collection.

Syntax

(contains hmap key)

Parameter(s)

The get method receives two parameters:

  1. hmap: The hash key and value.
  2. key: Keys being searched.

Return value

The contains method returns a boolean type. It returns true if the key is found and false if it is not found.

Example

Let's look at the code below:

(ns clojure.examples.example
(:gen-class))
(defn contains_s []
(def keys_s (hash-map "z" "1" "b" "22" "f" "53"))
(println (contains? keys_s "z"))
(println (contains? keys_s "x")))
(contains_s)

Explanation

In the code above:

  • Line 3: We define a contains_s function.
  • Line 4: We define a variable keys_s using the def keyword then we give it the collection(hashmap "z" "1" "b" "22" "f" "53").
  • Line 5: We use the println to print the value returned by the key z using the contains_s method. So we get true because the key z is present in the collection.
  • Line 6: We use the println to print the value returned by the key z using the contains_s method. So we get false because the key x is not present in the collection.
  • Line 7: We call the contains_s function.

Free Resources