hash-table-count
hash-table-count Function
Syntax:
hash-table-count hash-table → count
Arguments and Values:
hash-table—a hash table.
count—a non-negative integer .
Description:
Returns the number of entries in the hash-table. If hash-table has just been created or newly cleared (see clrhash) the entry count is 0.
Examples:
(setq table (make-hash-table)) → #<HASH-TABLE EQL 0/120 32115135>
(hash-table-count table) → 0
(setf (gethash 57 table) "fifty-seven") → "fifty-seven"
(hash-table-count table) → 1
(dotimes (i 100) (setf (gethash i table) i)) → NIL
(hash-table-count table) → 100
Affected By:
clrhash, remhash, setf of gethash
See Also:
hash-table-sizeNotes:
The following relationships are functionally correct, although in practice using hash-table-count is probably much faster:
(hash-table-count table) ≡
(loop for value being the hash-values of table count t) ≡
(let ((total 0))
(maphash #’(lambda (key value)
(declare (ignore key value))
(incf total))
table)
total)
Expanded Reference: hash-table-count
Basic Usage
hash-table-count returns the number of entries currently in the hash table.
(let ((ht (make-hash-table)))
(hash-table-count ht))
=> 0
(let ((ht (make-hash-table)))
(setf (gethash 'a ht) 1)
(setf (gethash 'b ht) 2)
(hash-table-count ht))
=> 2
Count Reflects Insertions and Removals
(let ((ht (make-hash-table)))
(setf (gethash 'x ht) 10)
(setf (gethash 'y ht) 20)
(setf (gethash 'z ht) 30)
(remhash 'y ht)
(hash-table-count ht))
=> 2
Updating an Existing Key Does Not Change Count
(let ((ht (make-hash-table)))
(setf (gethash 'a ht) 1)
(setf (gethash 'a ht) 999)
(hash-table-count ht))
=> 1
Count After clrhash
(let ((ht (make-hash-table)))
(dotimes (i 50)
(setf (gethash i ht) (* i i)))
(let ((before (hash-table-count ht)))
(clrhash ht)
(values before (hash-table-count ht))))
=> 50
=> 0
Count vs. Size
hash-table-count returns the number of stored entries, while hash-table-size returns the allocated capacity. Count is always less than or equal to size.
(let ((ht (make-hash-table :size 100)))
(dotimes (i 10)
(setf (gethash i ht) t))
(values (hash-table-count ht)
(<= (hash-table-count ht) (hash-table-size ht))))
=> 10
=> T