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();
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:
Example: obj.put<101, Rajesh>
obj.put<102, Ramesh>
- Remove a Pair from HashMap:
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.
{
System.out.println(variable.getKey() + “ ”+variable.getValue());
// the variable contain the Pair, So we use those method to extract the values &printing.
}
Comments
Post a Comment