Java Map Interface
In Java, the Map
interface is a collection that maps keys to values. Each key can map to at most one value, and the keys in a Map
must be unique. The Map
interface is part of the java.util
package and is implemented by several classes, including HashMap
, TreeMap
, and LinkedHashMap
.
Here are some of the most commonly used methods in the Map
interface:
void clear()
: This method removes all the key-value mappings from theMap
.boolean containsKey(Object key)
: This method returnstrue
if theMap
contains a mapping for the specified key, otherwisefalse
.boolean containsValue(Object value)
: This method returnstrue
if theMap
contains one or more mappings to the specified value, otherwisefalse
.Set<Map.Entry<K, V>> entrySet()
: This method returns aSet
view of the key-value mappings in theMap
.V get(Object key)
: This method returns the value to which the specified key is mapped, ornull
if the key is not mapped to any value.boolean isEmpty()
: This method returnstrue
if theMap
contains no key-value mappings, otherwisefalse
.Set<K> keySet()
: This method returns aSet
view of the keys in theMap
.V put(K key, V value)
: This method associates the specified value with the specified key in theMap
. If theMap
previously contained a mapping for the key, the old value is replaced with the new value and the old value is returned.void putAll(Map<? extends K, ? extends V> m)
: This method copies all of the mappings from the specifiedMap
to thisMap
.V remove(Object key)
: This method removes the mapping for the specified key from theMap
, if it is present.int size()
: This method returns the number of key-value mappings in theMap
.Collection<V> values()
: This method returns aCollection
view of the values in theMap
.
These methods provide the basic functionality to manipulate a Map
. The choice of which method to use depends on the specific requirements of the application.