Java HashMap

 HashMap:

  • HashMap contain data in form of : Keys & Values = Pair(we call it as Pair)
  • Key’s should be Unique and Values can be duplicate. The Keys and Values can be any DataType.
  • To Store Pairs in a variable that should be a “Map.Entry” DataType like Object datatype in ArrayList.
  • To read the values from the “Map.Entry Variable” we should use methods like: variable.getKey(); variable.getValue();


*Note:  the name of the Object becomes the name of the HashMap.


    ▪ HashMap Declaration: Two ways we can declare HashMap.

  • To Store any DataType of pairs(key, value): HashMap objectName = new HashMap();

Example: HashMap obj = new HashMap();


    2. To Store Required DataType of pairs(key, value):
         HashMap <key _DataType, value_DataType>  objectName = new HashMap             <key _DataType, value_DataType> ();

    Example:1. HashMap <Integer, String> obj = new HashMap <Integer, String();

                        //key is integer and value is string

   2. HashMap <String,Integer> obj= new HashMap <String, Integer>();

                        //key is string and value is integer.



  • Adding  Pairs into HashMap:
        To add Pairs to HashMap we use Method called put(key, value)” // we cannot             add pairs in between

        Example: obj.put<101, Rajesh>

obj.put<102, Ramesh>



  • Remove a Pair from HashMap:
        To remove Pairs from HashMap we use Method called  “remove(key)”

        Example: obj.remove(102);




  • Reading Pairs from HashMap:There are Two ways 
  • To list Pairs separated by “,”  just give the object name in print statement.
    Example: System.out.println(obj);// It print all the Pairs Stored in the HashMap like:                     [key1=value1, key2=value2, key3=value3]
   
     2. To list Pairs individually we use Loop statements like “for loop”(enhanced for             loop) and we use method called “entrySet()” which contain the Pairs.   
    
    Example: for(datatype variable: HashMapName.entrySet()) 
              //here the DataType Variable stores each value for every iteration of forLoop.

{

System.out.println(variable.getKey() +  +variable.getValue());

                // the variable contain the Pair, So we use those method to extract the                             values &printing.

}

Comments

Popular posts from this blog

Data-sly-list & Data-sly-repeat

Java Packages