Map

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:

  1. size(): Returns the number of key-value mappings in the map.
  2. isEmpty(): Returns true if the map contains no key-value mappings.
  3. containsKey(Object key): Returns true if the map contains a mapping for the specified key.
  4. containsValue(Object value): Returns true if the map maps one or more keys to the specified value.
  5. get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  6. put(K key, V value): Associates the specified value with the specified key in the map.
  7. remove(Object key): Removes the mapping for the specified key from the map if present.
  8. putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the specified map to this map.
  9. clear(): Removes all of the mappings from this map.
  10. keySet(): Returns a set view of the keys contained in the map.
  11. values(): Returns a collection view of the values contained in the map.
  12. entrySet(): Returns a set view of the mappings contained in the map.
Scroll to Top