Usage of HashMap and Iterating through the contents of a Map


Usage of HashMap

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..

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);

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.


Iterating through the contents of a Map

Maps provide methods which let you access the keys, values, or key-value pairs of the map as collections. You can iterate through these collections. Given the following map for example:

Map<String, Integer> usersMap = new HashMap<>();
usersMap.put("Alice", 500_000);
usersMap.put("Bob", 300_000);
usersMap.put("Charlie", 750_000);

Iterating through map keys

// Iterating through map keys:
for (String user : usersMap.keySet()) {
    System.out.println(user);
}

Result:

Alice
Bob
Charlie

keySet() provides the keys of the map as a Set. Set is used as the keys cannot contain duplicate values. Iterating through the set yields each key in turn. HashMaps are not ordered, so in this example the keys may be returned in any order.

Iterating through map values:

// Iterating through map values:
for (Integer salary : usersMap.values()) {
    System.out.println(salary);
}

Result:

500000
300000
750000

values() returns the values of the map as a Collection. Iterating through the collection yields each value in turn. Again, the values may be returned in any order.

Iterating through keys and values together

// Iterating through keys and values together:
for (Map.Entry<String, Integer> entry : usersMap.entrySet()) {
    System.out.printf("%s has a salary of %d\n", entry.getKey(), entry.getValue());
}

Result:

Alice has a salary of 500000
Bob has a salary of 300000
Charlie has a salary of 750000

entrySet() returns a collection of Map.Entry objects. Map.Entry gives access to the key and value for each entry.

Basic Programs