INTRODUCTION OF HashMap, LinkedHashMap, TreeMap Methods

Introduction HashMap Methods


How to remove Elements from map:

    We can remove elements from map in 2 ways.They are:-

  • remove( )

  • clear( )

remove ( ):

  • Remove( ) method will remove the specified key entry from the map. And return the removed element as output.

  • If passed key is not available then it will return null.

  • Syntax:

      public Object remove(Object key);

    If we use remove method for above example.

Example 1:

 
            
              {
                System.out.println(map); /* {Abc=123,XYZ=xyz, 55=55} */
                System.out.println(map.get("Abc")); /* 123 */
                System.out.println(map.get("XYZ")); /* xyz */
                System.out.println(map.remove("Abc")) /* 123 */
                System.out.println(map); /* {XYZ=xyz, 55=55} */
               /* at last line we only got two elements  from map  because we used remove() method once, */
               /* so it will remove that corresponding entry from map. */
              } 
                  

clear( ):

  • Clear( ) method will remove all elements from a map at a time.

  • Once if we call the clear( ) method then corresponding map will become empty.

  • Syntax:

      public void clear();

    If we use remove method for above example.

Example 2:

 
            
              {
                System.out.println(map); /* {Abc=123,XYZ=xyz, 55=55} */
                map.clear();
                System.out.println(map); /* {}// empty map */
                //If we want to find the map is empty or not .we should use  Empty( )
                System.out.println(is Empty( )); /* True */
              } 
                  
    Note
    • it will return true if Map is Empty. Else it will return false.

containsKey( ):

    Contains Key( ) method will return Boolean value, If map Contain specified key then it returns true else it will return false.

    Syntax:

      public boolean containsKey( Object key);

Example 3:

 
            
              HashMap  map1 = new HashMap();
              Map1.put(“name”, “SDJ”);
              boolean flag=map.containsKey( “name”);
              If(flag)
              {
                 System.out.println(map.get(“name”));//SDJ.
              } 
                  

containsValue():

    By using containsValue( ) method we can checks either the specified values are present in the map or not.If map contains the given values ,then it will return boolean true or else it will return false.

    Syntax:

      public boolean containsValues( Object value);

Example 4:

 
            
              new HashMap();
              map1.put(“name”, “SDJ”);
              boolean flag=map. containsValues( “SDJ”);
              If(flag)
              {
                 System.out.println( “is SDJ leaving center”+flag);
                 System.out.println( map.Size( )); /* 1 */
              } 
                  
    Note
    • In HashMap we have only one important drawback i.e. we can’t get order of output .

    • Map will allows duplicate keys and values

    • In order to overcome this draw back sun people came up with new class and it is named as LinkedHashMap.

LinkedHashMap:

  • It is one of the important class in map interface, it is almost same as the HashMap class except order of output.

  • It will give order of output based on the key, but not based on the values.

Example 5:

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

Output:

[Abc=123,XYZ=xyz,PQR=pqr,55=55]

TreeMap:

How to sort elements in the map Interface:

  • If we want to sort the elements in the map interface, we should go for TreeMap class.

  • In map we don’t have any other external method for sorting like collection .sort( )method.

  • If we want to sort the elements in Map, then map should contain same type of keys , Else we will get ClassCastException.

  • The TreeMap will not allow null keys.If we add the null object as a key to the TreeMap then we will get NullPointerException.

  • Tree map will sort the elements based on the key by using comparable interface in ascending order.

    Note
    • TreeMap will not allow null keys ,But it will allow null values.

Example 6:

 
            
              package com.sdj.pack1;
              import java.util.TreeMap;
              public class TreeMapExp 
              {
                 public static void main(String[] args)
                 {
                    TreeMap map=new TreeMap();
                    map.put( "Abc", "123");
                    map.put( "$XYZ", "xyz");
                    map.put( "PQR", "pqr");
                    map.put( "pqr", "pqr");
                    map.put( "55", "55");
                    map.put( "null", "null");
                    /* here null is added as String obj ,But not original null obj */
                    System.out.println(map.get("Abc")); /* Abc */
                    System.out.println(map.get("XYZ")); /* XYZ */
                    System.out.println(map.get("PQR")); /* pqr */
                    System.out.println(map.get("55")); /* 55 */
                    System.out.println (map);
                 }
              } 
                   

Output:

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

Example 7:

 
            
              package com.sdj.pack1;
              import java.util.TreeMap;
              public class TreeMapExp 
              {
                 public static void main(String[] args)
                 {
                    Treemap map=new Treemap( );
                    map.put( "Abc", "123");
                    map.put( "XYZ", "xyz");
                    map.put( 55, "55"); /* here: class cost Exception */
                    System.out.println(map);
                 }
              } 
        
                  
    Note
    • Here we will get ClassCastException , why because for sorting we should use same type of keys, but here we are using keys of different datatypes .

headMap( ):

    This method will return the headmap from given input key, If the key is not found then it will return headmap from where the key is present.

Example 8:

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

Output:

{$XYZ=xyz, 55=55, Abc=123, PQR=pqr, null=null, pqr=Abc} {$XYZ=xyz, 55=55, Abc=123 } {$XYZ=xyz }
    Note
    • the output for key =”123”, but “123 ” is not there, even though it not there, it will return the value from where it is present. Since if it there it can present before key=”55” , since we got only $XYZ=xyz value is out put.

tailMap ( ):

    It works same as headMap(),But it will return tail map from given key position after sorting.It’s rule is same as that of tail set.

Syntax:

    public SortedMap tailMap(object start key);

Example 9:

 
            
              package com.sdj.pack1;
              import java.util.TreeMap;
              public class HeadMapExp
              {
                 public static void main(String[] args)
                 {
                    Treemap map=new Treemap( );
                    map.put( "10", "20");
                    map.put( "70", "20");
                    map.put( "60", "70");
                    map.put( "40", "20");
                    map.put( "80", "60");
                    System.out. println (map);
                     System.out. println (map.tailmap(40));
                 }
              } 
                   

Output:

{10=20, 40=20, 60=70, 70=20, 80=60} {40=20, 60=70, 70=20, 80=60}
    Note
    • tail map will take input as starting key and return all remaining keys till the end from starting.

    • tailMap will take input key as include operation.

    • headMap will take input key as exclude operation.

subMap (from key ,to key):

Syntax:

    public SortedMap subMap(Object staring key, Object ending key)

 
            
              package com.sdj.pack1;
              import java.util.TreeMap;
              public class HeadMapExp
              {
                 public static void main(String[] args)
                 {
                    TreeMap map=new TreeMap( );
                    map.put( "10", "20");
                    map.put( "70", "20");
                    map.put( "60", "70");
                    map.put( "40", "20");
                    map.put( "80", "60");
                    System.out. println (map);
                    System.out. println (map.subMap(“40”,”70”));
                 }
              } 
                   

Output:

{10=20, 40=20, 60=70, 70=20, 80=60} {40=20, 60=70}
    Note
    • In the submap starting key is included and ending key is excluded.

firstKey ( ) :

    This method will return first element after sorting of keys in the map.

Syntax:

    public object firstKey( );

lastKey ( ):

    method will return last element from map, after sorting of keys in the map.

Syntax:

    public object firstKey( );