November 26, 2015

Map Interface

Map is very unique and very much useful interface of the collection framework and also a very helpful in very big and complex applications of the java technology.

Map is an interface which maintains data in Key,Value pair. Both key and value are type of Object. Which means we can make any type of data as Key and any type data as Value. But very important thing is that Map contains unique key. Each and every key has some value.

AbstractMap is the abstract class which implements Map interface and HashMap is the concrete sub class of  AbstractMap. TreeMap is an interface which implements SortedMap.

Following is the list of methods provided by Map interface.


  1. put(Object key, Object value)
  2. get(Object key)
  3. size()
  4. clear()
  5. isEmpty()
  6. putAll(Map)
  7. getKey()
  8. getValue()
  9. setValue()


Map.Entry Interface

Map.Entry interface is an interface which is nested interface of Map interface. It generally used for getting key and value from map separately. Following is a simple example which shows the use of Map.Entry interface.

import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

class MapDemo
{
public static void main(String[] ar)
{
HashMap hm = new HashMap();
hm.put("India",95);
hm.put("China",100);
hm.put("Srilanka",5);
hm.put("Austrila",70);

Set s = hm.entrySet(); // Method 1
Iterator i = s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
System.out.println("\n");
for(Object o : s) // Method 2
{
System.out.println(o);
}
System.out.println("\n");
for(Object o : s) // Method 3
{
Map.Entry me = (Map.Entry)o;
System.out.println(me.getKey() + " " + me.getValue());
}
}
}

No comments:

Post a Comment