What is Map in java?

Map is an interface which facilitates to store only unique elements.It stores key value pair as an element.Each pair is known as an entry.

Map.Entry is the subinterface of Map.It provides methods getKey() and getValue() to get key and value.

Methods of Map interface:

  • public Object put(object key,Object value): is used to insert an entry in the map.
  • public void putAll(Map map):is used to insert the given map in the map.
  • public Object remove(object key):is used to delete an entry for the given key.
  • public Object get(Object key):is used to return the value for the given key.
  • public boolean containsKey(Object key):is used to search the given key from the map.
  • public boolean containsValue(Object value):is used to search the given value from the map.
  • public Set keySet():returns the Set view containing all the keys.
  • public Set entrySet():returns the Set view containing all the keys and values.

The most commonly implementation of Map interface is HashMap. It implements the Map interface and extends AbstractMap class.


package expertwebindia;
import java.util.*;
class CollectionTestExample{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"Sunil");
hm.put(2,"Raj");
hm.put(3,"Rahul");
//entrySet() method returns Map.Entry
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

 

Leave a Reply