Skip to content

HashMap

Key-value store with string keys.

Methods

MethodReturnsDescription
HashMap.new()mapCreate empty map
set(key, val)Set value (string)
get(key)stringGet value ("" if missing)
has(key)boolKey exists
remove(key)Delete entry
len()intEntry count
keys()[string]Array of all keys
values()[string]Array of all values
clear()Remove all entries

Examples

wyn
var m = HashMap.new()
m.set("name", "Wyn")
m.set("version", "2")

println(m.get("name"))                  // Wyn
println(m.has("name").to_string())      // true
println(m.len().to_string())            // 2

Map Literals

Build a map inline with {key: value}. Values are typed by the literal, so a map of ints yields ints back from m[k] and m.get(k):

wyn
var scores = {"alice": 90, "bob": 85}
println(scores["alice"].to_string())    // 90
println(scores.get("bob").to_string())  // 85

Index and Membership

Read a value with m[key], and test for a key with in / not in:

wyn
var m = {"host": "localhost", "port": "8080"}
println(m["host"])                      // localhost

if "host" in m { println("host set") }
if "user" not in m { println("no user") }

Iteration

Iterate a map directly — for k, v in m binds both key and value, and for k in m iterates the keys:

wyn
var m = {"name": "Wyn", "version": "2"}

for k, v in m {
    println("${k}: ${v}")
}

for k in m {
    println(k)
}

You can also iterate the key array from keys():

wyn
for k in m.keys() {
    println("${k}: ${m.get(k)}")
}

Values

wyn
var vs = m.values()
for v in vs {
    println(v)
}

Global Access

HashMap variables can be accessed from functions:

wyn
var config = HashMap.new()

fn setup() {
    config.set("host", "localhost")
    config.set("port", "8080")
}

fn get_url() -> string {
    return config.get("host") + ":" + config.get("port")
}

setup()
println(get_url())  // localhost:8080

See Also

  • Arrays — ordered collections
  • JSON — parse JSON into HashMaps
  • Database — persistent key-value storage

MIT License — v1.16