vimwiki

Java hashmap

Store collection of key-value pairs.

Creation

We import the hashmap and declare it by specifying both the key and the value data type.

!! cannot use primitive

import java.util.HashMap;
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();

Adding key-value pair

myHashMap.put("foo", 1);

Accessing

Use .get() with the key.

myHashMap.get("foo");

Removing a value

Use .remove() with the key;

myHashMap.remove("foo");

Removing all

myHashMap.clear();

Size

myHashMap.size();

Traversing

Use a for-each loops

for(String key : myHashMap.keySet()) {
    // code
}

Other methods

containsKey()

myHashMap.containsKey(key);

replace()

myHashMap.replace(key, value);

keySet()

Create a Set with all the keys in the hashmap.

myHashMap.keySet();

values()

Return a collection with all the values (without their key).

myHashMap.values();