Friday, 1 May 2015

Java Map Interface

Java Map Interface
A map contains values based on the key i.e. key and value pair.Each pair is known as an entry.Map contains only unique elements.
Commonly used methods of Map interface:
  1. public Object put(object key,Object value): is used to insert an entry in this map.
  2. public void putAll(Map map):is used to insert the specified map in this map.
  3. public Object remove(object key):is used to delete an entry for the specified key.
  4. public Object get(Object key):is used to return the value for the specified key.
  5. public boolean containsKey(Object key):is used to search the specified key from this map.
  6. public boolean containsValue(Object value):is used to search the specified value from this map.
  7. public Set keySet():returns the Set view containing all the keys.
  8. public Set entrySet():returns the Set view containing all the keys and values.

Entry
Entry is the subinterface 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.

Java HashMap class

  • A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.

Hierarchy of HashMap class:



Example of HashMap class:

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

Output:102 Rahul
       100 Amit
       101 Vijay

What is difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key and value).


No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...