0% completed
The HashMap class in Java provides a variety of operations to manage key-value pairs efficiently. In this lesson, we will explore common operations on a HashMap, including inserting/updating elements, removing elements, retrieving data, performing bulk operations, and iterating over the map. Each section includes an explanation, the syntax for the operation, and a code example with a bullet-point explanation.
In HashMap, you insert elements using the put()
method. This method associates a specified value with a specified key. If the key already exists, the new value replaces the old one, and the previous value is returned.
V put(K key, V value);
key
: The key with which the specified value is to be associated.value
: The value to be associated with the key.null
if there was no mapping.Example Explanation:
HashMap<String, Integer>
called studentGrades
is created.put()
method adds key-value pairs: "Alice" → 85, "Bob" → 90, "Charlie" → 78.put("Alice", 88)
updates Alice’s grade and returns the previous value (85).To remove an element from a HashMap, use the remove()
method. You can remove an element by specifying its key. If the key exists, the method removes the key-value pair and returns the associated value.
V remove(Object key);
key
: The key of the element to be removed.null
if the key was not found.Example Explanation:
remove("Bob")
call removes the key "Bob" and returns his grade (90).HashMap provides various methods to retrieve data:
values()
, and entrySet()
return views of the keys, values, and key-value pairs, respectively.V get(Object key);
boolean containsKey(Object key);
Set<K> keySet();
Example Explanation:
get("Alice")
retrieves Alice’s grade.containsKey("David")
checks for the key "David" and returns false.keySet()
and values()
provide sets of keys and values, respectively.Bulk operations enable you to work with multiple entries at once. Common bulk operations include:
putAll(Map<? extends K, ? extends V> m)
:clear()
:void putAll(Map<? extends K, ? extends V> m);
void clear();
Example Explanation:
putAll()
method copies all entries from map2
into map1
.clear()
method removes all key-value pairs from map1
......
.....
.....