Advanced Java: Collections, Generics and More ยท The Collections Framework
Store values under keys, replace them, read missing keys safely, and loop over every entry.
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 5);
stock.put("pear", 2);
stock.put("apple", 8); // same key: the value is replaced
int apples = stock.get("apple");
Integer kiwis = stock.get("kiwi"); // missing key: null
boolean hasPear = stock.containsKey("pear");
int total = 0;
for (Map.Entry<String, Integer> e : stock.entrySet()) {
total += e.getValue();
}
System.out.println(apples + " " + kiwis + " " + hasPear + " " + total);
}
}apple with the value 5 is added to the HashMap that stock points to.pear with the value 2 is added to the HashMap that stock points to.apples is created on the stack with the value 8.hasPear is created on the stack with the value true.total is created on the stack with the value 0.e is created on the stack and points to a new HashMap$Node on the heap: apple=8.e is created on the stack and points to a new HashMap$Node on the heap: pear=2.total changes from 8 to 10. e goes out of scope and disappears.for (Map.Entry<String, Integer> e : stock.entrySet()).8 null true 10.