Map Interface java

Map store elements in the form of key and value pare. If the key is provided then its corresponding value can be obtained. The key should have unique values.

HashMap and TreeMap classes provide implementation of Map interface

Difference between HashMap and TreeMap are its internal data structure. HashMap uses Hash Table whereas TreeMap uses Binary Search Tree for storing elements. Functionality of Map is represented by Map interface which not extends Collection interface and adds following methods-

Commonly used methods of Map interface:

SN Method Description
1 put() Is usedalign to store an entry to a map. Key and value pair is called an entry.
public boolean put(Object key, Object value)
2 get() Is used to obtain a value from a Map.public Object get(Object key)
3 remove() Is used to remove an entry form a Map. public boolean remove(Object key)
3 containsKey() Is used to search a key in a Map. public boolean containsKey(Obejct key)
4 containsValue() Is used to search a value in a Map. public boolean containsValue(Object key)
5 size() Is used to find out number of entries in a Map.public int size()
6 clear() Is used to remove all the entries from a Map.public void clear()
7 keySet() Is used to obtain a Set view for all the keys of a Map.public Set key set()
second
8 entrySet() Is used to find out all the entries of a Map in a Set.public Set entrySet()
second
A Set which is return by entrySet() method contains object of type Map.Entry. Entry is an nested interface of Map. All Map implementations provide implementation of Entry interface. Entry interface has following methods-

1- getKey() : Is used to obtain key of an entry. public Object getKey()

2- getValue() : Is used to obtain value of an entry. public Object getValue()

Entry

Entry is the sub interface of Map.So we will access it by Map.Entry name.It provides methods to get key and value.

Methods of Entry interface:

  1. public Object getKey():is used to obtain key
  2. public Object getValue():is used to obtain value.