Java Map Interface

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Map Interface

A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys.

Map is useful if you have to search, update or delete elements on the basis of key.

Useful methods of Map interface

Method

Description

Object put(Object key, Object value)

It is used to insert an entry in this map.

void putAll(Map map)

It is used to insert the specified map in this map.

Object remove(Object key)

It is used to delete an entry for the specified key.

Object get(Object key)

It is used to return the value for the specified key.

boolean containsKey(Object key)

It is used to search the specified key from this map.

Set keySet()

It is used to return the Set view containing all the keys.

Set entrySet()

It is used to return the Set view containing all the keys and values.

Map.Entry Interface

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

Methods of Map.Entry interface

Method

Description

Object getKey()

It is used to obtain key.

Object getValue()

It is used to obtain value.

Java Map Example: Generic (New Style)

  1. import java.util.*;  
  2. class MapInterfaceExample{  
  3.  public static void main(String args[]){  
  4.   Map map=new HashMap();  
  5.   map.put(100,"Amit");  
  6.   map.put(101,"Vijay");  
  7.   map.put(102,"Rahul");  
  8.   for(Map.Entry m:map.entrySet()){  
  9.    System.out.println(m.getKey()+" "+m.getValue());  
  10.   }  
  11.  }  
  12. }  

Output:

102 Rahul
100 Amit
101 Vijay

Java Map Example: Non-Generic (Old Style)

  1. //Non-generic  
  2. import java.util.*;  
  3. public class MapExample1 {  
  4. public static void main(String[] args) {  
  5.     Map map=new HashMap();  
  6.     //Adding elements to map  
  7.     map.put(1,"Amit");  
  8.     map.put(5,"Rahul");  
  9.     map.put(2,"Jai");  
  10.     map.put(6,"Amit");  
  11.     //Traversing Map  
  12.     Set set=map.entrySet();//Converting to Set so that we can traverse  
  13.     Iterator itr=set.iterator();  
  14.     while(itr.hasNext()){  
  15.         //Converting to Map.Entry so that we can get key and value separately  
  16.         Map.Entry entry=(Map.Entry)itr.next();  
  17.         System.out.println(entry.getKey()+" "+entry.getValue());  
  18.     }  
  19. }  
  20. }  

Output:

1 Amit
2 Jai
5 Rahul
6 Amit