Java Map Syntax
Map is an interface in the java.util package. A map is declared with two types: K for the keys and V for the values.
What is the difference between Map and HashMap?
Map is the interface that defines the operations. HashMap is a class that implements Map with a hash table and makes no guarantees about the order of its keys. TreeMap is another implementation that keeps its keys sorted.
Java Map Examples
The following are examples of using a Map in Java. Run them in the online Java code runner to see what each method returns.
Add and read values
put() adds a key-value pair. If the key is already in the map, put() replaces its value. get() returns null for a missing key, and getOrDefault() returns the default value you pass.
Check and remove keys
containsKey() tells whether a key is in the map, remove() deletes the pair for a key, and size() returns the number of pairs.
Loop through a Map
entrySet() returns the key-value pairs as a Set that a for-each loop can walk through. A HashMap returns the pairs in no guaranteed order. A TreeMap, as in this example, returns them sorted by key.