INTRODUCTION OF MAP AND HASHMAP

Introduction Of Map


Map Interface

    Map is an important interface in collection frameworks. But Map is not part of the collection interface. It is separate module in collection framework.

  • Map will work based on the “key” and “value” pair.

    key =value

  • Map will allow “duplicate keys” and value.

    Key1=value1

    Key1=value2

    Key2=value1

  • If we use the duplicate key then old value gets replaced with new value.From above example key1 will contain “value2”,means for key1 first we are setting value as “value1”but after that for same key we are using another value. In this case the latest value will become as current value for the duplicate key.

  • Map will allows null values.

    Key1 =null;

    Key2=null;

  • Map will allow null as a key.

    Null=xyz

    Null=abc.

  • Set interface won’t give ordered output why because here there is no index based iteration we should iterate through the Iterator interface (or) ListIterator interface there is no other way.

  • Map contains 4 important sub classes ,they are shown in below hierarchy .They are all available in java.util package.

    Naming Convention
    Map

HashMap:

  • HashMap also works based on key and value pair only.

  • Once we set the value for the key we can access that value anywhere by Using corresponding “key”.

  • HashMap interface don’t support index based operation.

Adding elements to HashMap:

    we can add elements to HashMap in various ways as below.

put( ):

  • put( ) will associate the specified key in HashMap.If the HashMap contains key value more than one time then old time old value Get replaced with new time new value.

  • Syntax:

      public object put(object key, object value)

Example 1:

 
            
              package com.sdj.pack1;
              import java.util.HashMap;
              public class MapExp 
              {  
                public static void main(String[] args)
                {
                  HashMap  person=new HashMap();
                  person.put("name", "Ram");
                  person.put("Age", "27");
                  person.put("Addresss", "SDJ");
                  person.put("Course", "J2ee");
                  System.out.println(person);
                }
              } 
                

Output:

[Address=SDJ, curse=j2ee, Age=27, name=Ram]

Adding elements by using putAll( );

Syntax:

    public void putAll(Map, map);

Example 2

 
            
              package com.sdj.pack1;
              import java.util.HashMap;
              public class MapExp1 
              {
                public static void main(String[] args)
                { 
                  HashMap person1=new HashMap();
                  person1.put("name", "Ram");
                  person1.put("Age", "27");
                  person1.put("Addresss", "SDJ");
                  person1.put("Course", "J2ee");
                  HashMap person2=new HashMap();
                  person2.putAll(person1);
                  System.out.println(person2);
                }
              } 
                   

Output:

[Address=SDJ, course=j2ee, Age=27, name=Ram]

Explanation:

  • Here putAll() method will take another Map object as input and Adds all objects as individual elements into new HashMap object.From the above example we are passing person1 hashmap obj into person2 hashmap object by using putAll().so it adds all objects which are available in person1 hashmap object to person2 hashmap object.

Example 3:

 
            
              package com.sdj.pack1;
              import java.util.HashMap;
              public class MapExp2
              {
                public static void main(String[] args)
                {
                  HashMap map=new HashMap();
                  map.put("null", "null");/* HashMap will allows null object is keys and values also.*/ 
                  map.put("abc","123");
                  HashMap map1=new HashMap();
                  map1.put("xyz", map);
                  map1.putAll(map1);
                  System.out.println(map);
                  System.out.println(map1);
                }
              } 
                   

Output:

[null=null, Abc=123] [XYZ={null=null, Abc=123}, null=null, Abc=123]

How to get the value from HashMap?

    We can iterate the values from HashMap by passing the key as input.There are 4 ways to access values from the HashMap, they are

  • get(object key);

  • entry Set();

  • keySet();

  • values();

get (object key):

  • By using get() method we can retrieve the value from HashMap by passing KEY as input and it will return output value as Object class type for the corresponding Key.

  • get() will return corresponding value as output if the given KEY is found/exist,Else it will return output as null object.

  • Syntax:

      public Object get(Object key)

Example 4:

 
            
              package com.sdj.pack1;
              import java.util.HashMap;
              public class MapExp3 
              {
                public static void main(String[] args)
                {
                  HashMap map=new HashMap();
                  map.put( "Abc", "123");
                  map.put( "XYZ", "xyz");
                  map.put( "PQR", "pqr");
                  map.put( "55", "55");
                  System.out.println(map.get("Abc"));
                  System.out.println(map.get("XYZ"));
                  System.out.println(map.get("PQR"));
                  System.out.println(map.get("54"));
                  System.out.println(map);
                }
              } 
                   

Output:

123 xyz pqr null {XYZ=xyz, 55=55, Abc=123, PQR=pqr}

entrySet( ):

  • Entryset( ) will return all HashMap values as Set interface.or

  • Map interface will return output as Set interface type for entrySet() by adding all values as elements to the corresponding Set object

  • Syntax:

      public Set entrySet();

 
            
              package com.sdj.pack1;
              import java.util.HashMap;
              import java.util.Map;
              import java.util.Set;
              public class MapExp4 
              {
                 public static void main(String[] args)
                 {
                    HashMap map1=new HashMap();
                    map1.put("Abc","123");
                    map1.put("XYZ","xyz");
                    map1.put("55","55");
                    System.out.println(map1.get("Abc")); /* 123 */
                    System.out.println(map1.get("XYZ")); /* xyz */
                    Set valueSet=map1.entrySet();
                    /* printing Map values from Set object through sop: */
                    System.out.println(valueSet);
                    /* output:{123,xyz,55}  these are values of Map interface. */
                    for(Object element:valueSet)
                    {
                    /* printing Map values from Set object through enhanced for loop: */
                       System.out.println(element);
                    }
                 }
              } 
                   

Output:

123 xyz 55

If you want printing Map values from Set object through Iterator:

 
            
              SetvalueSet = map.entrySet();// here map refer from above expl
              Iterator  it = valueset.iterator();
              /* Valueset.add(“Raj”);  // here we will get ConcurrentModificationException. */
              While(it.hashnext())
              {
                 System.out.println(it.next());
              } 
                   

Output:

xyz 55 123
    Note
    • If we try to modify collection of objects after creating Iterator object before finishing iteration We will get” ConcurrentModificationException”.

    Note
    • Iterator interface is only applicable for List and Set only, But it isn’t applicable for Map interface, Since we can’t able to use Iterator directly from Map interface.

3rd way of Reading elements from map is By using keySet( ):

Syntax:

    public Set keySet( )

KeySet():

This method will works same as the entrySet() method. It will return the Set interface while adding all map keys to Set interface object like entrySet() adds all Map value to Set interface.

Example 5:

 
            
              package com.sdj.pack1;
              import java.util.HashMap;
              import java.util.Set;
              public class MapExp5
              {
                 public static void main(String[] args)
                 {
                    HashMap map =new HashMap();
                    map.put( "Abc", "123");
                    map.put( "XYZ", "xyz");
                    map.put( "55", "55");
                    Set keySet = map.keySet();
                    /* System.out.println(keySet);//Output:{Abc, XYZ,55} */
                    for(Object key:keySet)
                    {
                       System.out.println(key+"="+map.get(key));
                    }
                 }
              } 
                   

Output:

Abc=123 XYZ=xyz, 55=55
    Note
    • we will get key from keySet ,then by using that key, we gets value from map by using get()

If you want printing Map values from keySet through Iterator:

 
            
              Iterator it=keyset.iterator( );
              While(it.hashnext())
              {
                 Object key = it.next());
                 System.out.println(key+”=”+map.get(key));
              } 
                   

Output:

Abc=123 55=55 XYZ=xyz