In Java, maps are interfaces that define collections that map keys to values. The primary interfaces related to maps in Java are Map
, SortedMap
, NavigableMap
, and ConcurrentMap
. Here’s a summary of their syntax and methods:
Map Interface
The Map
interface represents a basic mapping from keys to values. It does not guarantee any specific order of the elements.
public interface Map<K, V> {
// Methods
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
V get(Object key);
V put(K key, V value);
V remove(Object key);
void putAll(Map<? extends K, ? extends V> m);
void clear();
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
// Inner interface for Map entries
interface Entry<K, V> {
K getKey();
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();
}
}
Code language: PHP (php)
Methods:
- size(): Returns the number of key-value mappings in the map.
- isEmpty(): Returns true if the map contains no key-value mappings.
- containsKey(Object key): Returns true if the map contains a mapping for the specified key.
- containsValue(Object value): Returns true if the map maps one or more keys to the specified value.
- get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
- put(K key, V value): Associates the specified value with the specified key in the map.
- remove(Object key): Removes the mapping for the specified key from the map if present.
- putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the specified map to this map.
- clear(): Removes all of the mappings from this map.
- keySet(): Returns a set view of the keys contained in the map.
- values(): Returns a collection view of the values contained in the map.
- entrySet(): Returns a set view of the mappings contained in the map.