Usage of HashMap

suggest change

HashMap is an implementation of the Map interface that provides a Data Structure to store data in Key-Value pairs.

1. Declaring HashMap

Map<KeyType, ValueType> myMap = new HashMap<KeyType, ValueType>();

KeyType and ValueType must be valid types in Java, such as - String, Integer, Float or any custom class like Employee, Student etc..

For Example : Map<String,Integer> myMap = new HashMap<String,Integer>();

2. Putting values in HashMap.

To put a value in the HashMap, we have to call put method on the HashMap object by passing the Key and the Value as parameters.

myMap.put("key1", 1);
myMap.put("key2", 2);

If you call the put method with the Key that already exists in the Map, the method will override its value and return the old value.

3. Getting values from HashMap.

For getting the value from a HashMap you have to call the get method, by passing the Key as a parameter.

myMap.get("key1");    //return 1 (class Integer)

If you pass a key that does not exists in the HashMap, this method will return null

4. Check whether the Key is in the Map or not.

myMap.containsKey(varKey);

5. Check whether the Value is in the Map or not.

myMap.containsValue(varValue);

The above methods will return a boolean value true or false if key, value exists in the Map or not.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Collections:
* Usage of HashMap
* Stacks

Table Of Contents
4 Collections
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap