Skip to content
nmtuan2001 edited this page Oct 11, 2021 · 3 revisions

HashMap is a part of Java's collection and this class can be found in java.util package. It allows us to store a key-value pair and access them by an index of another type. One object is used as a key (index) to another object (value). If we try to insert a duplicate key, it will then replace the element of the corresponding key.

// IMPORT
import java.util.HashMap;

// PUT 
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("firstKey", 1);
hashMap.put("secondKey", 2);
hashMap.put("thirdKey", 3);

// GET
int value = hashMap.get("firstKey");

// REMOVE
hashMap.remove("secondKey");

// CHECK
hashMap.containsKey("thirdKey");

// ITERATE USING FOR EACH
for (String key : hashMap.keySet()) {
    System.out.println(hashMap.get(key));
}
Clone this wiki locally