Grav v1.14.0

HashMap

import "std/collections" (included in import "std") · namespace std.collections

HashMap<K, V> maps keys to values with O(1) average lookups, inserts and removals (open addressing with linear probing). It is the map to use by default.

  • {"a": 1, "b": 2} builds a HashMap (through mapOf).
  • m[k] = v adds or replaces; m[k] reads. A missing key reads as the value type's zero value (0, "", false, null), so use containsKey, getOr or getOrPut when keys may be missing.
  • Keys can be integers, bool, float, strings, enums and objects. Objects are matched by identity (the same object), not by operator==.
  • Iteration order is not defined. Use Map for insertion order or SortedMap for sorted keys.
grav
import "std"

fn main() {
    let stock = {"apple": 3, "pear": 0}
    stock["fig"] = 12
    stock["apple"] += 2
    print(stock["apple"])
    print(stock.size())
    print(stock.containsKey("kiwi"))
    print(stock.getOr("kiwi", -1))
    stock.remove("pear")

    let keys = stock.keys()
    Sort.sort(keys)
    for (k in keys) { print("${k}: ${stock[k]}") }

    let counts = new HashMap<string, int>()
    for (w in Str.words("to be or not to be")) {
        counts[w] = counts.getOr(w, 0) + 1
    }
    print("${counts["to"]} ${counts["be"]} ${counts["or"]}")
}
Output
5
3
false
-1
apple: 5
fig: 12
2 2 1

keys() and values() return copies.

entries() gives the key-value pairs (destructure them in a loop), putAll merges another map in, removeWhere and filter select by key and value:

grav
import "std"

fn main() {
    let stock = {"apple": 3, "pear": 0, "fig": 12}
    stock.putAll({"kiwi": 5})
    print(stock.removeWhere(fn(name, n) => n == 0))
    let es = stock.entries()
    es.sortBy(fn(a, b) => Str.compare(a.first, b.first))
    for ((name, n) in es) { print("${name}: ${n}") }
    print(stock.filter(fn(name, n) => n > 4).size())
}
Output
1
apple: 3
fig: 12
kiwi: 5
2

API

class HashMap<K, V> implements Iterable<Entry<K, V>>

Constructors

  • new HashMap()

Methods

  • fn put(key: K, value: V) — Sets the value for key (adding the key, or replacing its value).
  • fn get(key: K) -> V — The value for key, or the zero value of V when absent.
  • fn getOr(key: K, fallback: V) -> V — The value for key, or fallback when the key is missing.
  • fn containsKey(key: K) -> bool — Whether the map has key.
  • fn operator[](key: K) -> V — map[key]: the value for key.
  • fn operator[]=(key: K, value: V) — map[key] = value: sets the value for key.
  • fn remove(key: K) -> bool — Removes key; re-inserts the rest of its probe run so lookups stay correct.
  • fn size() -> int — The number of keys.
  • fn length() -> int — The number of keys (same as size()).
  • fn isEmpty() -> bool — Whether the map has no keys.
  • fn clear() — Removes every key and value.
  • fn toString() -> string — As text: {"a": 1, "b": 2} (strings in quotes).
  • fn keys() -> Array<K> — The keys, as a new array (in no particular order).
  • fn iterator() -> HashMapIterator<K, V> — Every key with its value, one at a time (in no particular order): what for ((k, v) in map) uses. Adding to the map while walking it may skip or repeat entries.
  • fn forEach(f: fn(K, V)) — Calls f with each key and its value (in no particular order).
  • fn getOrPut(key: K, fallback: V) -> V — The value for key, inserting fallback first when absent.
  • fn values() -> Array<V> — The values, as a new array (in the same order as keys()).
  • fn entries() -> Array<Pair<K, V>> — Every key with its value, as pairs (in no particular order).
  • fn putAll(other: HashMap<K, V>) — Copies every entry of other into this map (replacing values of shared keys).
  • fn removeWhere(f: fn(K, V) -> bool) -> int — Removes the entries for which f(key, value) holds; returns how many.
  • fn filter(f: fn(K, V) -> bool) -> HashMap<K, V> — A new map with the entries for which f(key, value) holds.

class HashMapIterator<K, V> implements Iterator<Entry<K, V>>

Walks a HashMap's entries, slot by slot.

Constructors

  • new HashMapIterator(map: HashMap<K, V>)

Methods

  • fn hasNext() -> bool
  • fn next() -> Entry<K, V>

class HashKeyIterator<K, V> implements Iterator<K>

Walks a HashMap's keys, slot by slot (HashSet's iterator).

Constructors

  • new HashKeyIterator(map: HashMap<K, V>)

Methods

  • fn hasNext() -> bool
  • fn next() -> K

Functions

  • fn hashOf(x: int) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: long) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: string) -> long — A hash of the string's contents, used by HashMap and HashSet keys.
  • fn hashOf(x: uint) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: ulong) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: byte) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: bool) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: float) -> long — A hash of the value, used by HashMap and HashSet keys.
  • fn hashOf(x: any) -> long — Anything else that fits in an any: objects hash by identity (matching their ==), enums by value, so HashMap<MyClass, V> and HashMap<MyEnum, V> work too.
  • fn mapOf<K, V>(...pairs: Pair<K, V>) -> HashMap<K, V> — A HashMap holding the pairs: what a map literal {"a": 1, "b": 2} builds.

Edit this page on GitHub