Grav v1.14.0

Map

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

Map<K, V> keeps keys in the order they were first added. It stores keys and values in two arrays and looks keys up with ==, so lookups are O(n): fine for small maps (configuration, a handful of options), and the only map whose keys can be any type with ==. For large maps use HashMap.

grav
import "std"

fn main() {
    let headers = new Map<string, string>()
    headers["Host"] = "example.com"
    headers["Accept"] = "*/*"
    headers["Host"] = "grav.dev"       // replaces, keeps the position
    print(headers)
    print(headers.keys())
    print(headers.getOr("Cookie", "none"))
    headers.forEach(fn(k, v) { print("${k}: ${v}") })
}
Output
{"Host": "grav.dev", "Accept": "*/*"}
["Host", "Accept"]
none
Host: grav.dev
Accept: */*

Unlike HashMap, Map.get(key) with a missing key throws NotFound; m[key] and getOr do not.

API

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

Constructors

  • new Map()

Methods

  • fn put(key: K, value: V) — Sets the value for key (adding it at the end, or replacing its value).
  • fn get(key: K) -> V — The value for key (NotFound when missing).
  • fn operator[](key: K) -> V — m[key]: the value for key (NotFound when missing).
  • fn operator[]=(key: K, value: V) — m[key] = value: sets the value for key.
  • fn getOr(key: K, fallback: V) -> V — The value for key, or fallback when missing.
  • fn containsKey(key: K) -> bool — Whether the map has key.
  • fn remove(key: K) -> bool — Removes key; whether it was there.
  • fn size() -> int — The number of keys.
  • fn length() -> int — The number of keys (same as size()).
  • fn isEmpty() -> bool — Whether the map is empty.
  • fn clear() — Removes every key.
  • fn toString() -> string — Copies, in insertion order (changing them does not affect the map). As text: {"a": 1, "b": 2} (strings in quotes).
  • fn keys() -> Array<K> — The keys in insertion order (a copy).
  • fn values() -> Array<V> — The values in insertion order (a copy).
  • fn forEach(f: fn(K, V)) — Calls f with each key and value, in insertion order.
  • fn getOrPut(key: K, fallback: V) -> V — The value for key, inserting fallback first when absent.
  • fn iterator() -> EntryIterator<K, V> — Every key with its value, one at a time, in insertion order: what for ((k, v) in map) uses.
  • fn entries() -> Array<Pair<K, V>> — Every key with its value, as pairs, in insertion order.
  • fn putAll(other: Map<K, V>) — Copies every entry of other into this map.

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

Walks keys and values kept side by side in two arrays (Map, SortedMap), as pairs.

Constructors

  • new EntryIterator(ks: Array<K>, vs: Array<V>)

Methods

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

Edit this page on GitHub