The Java Collections framework provides the Java HashMap data structure, which implements the Map interface. It is used to hold key-value pairs, each of which is unique. HashMap enables speedy retrieval, insertion, and deletion of key-value pairs, making it ideal for activities requiring quick access to data based on a specific key.
Why HashMap?
- Unordered: HashMap does not retain element order based on insertion order or any other criteria. If you need to keep order, you can use LinkedHashMap, a HashMap subclass that supports insertion orders.
- Hash-based: HashMap computes the hash code of keys using a hash function, which is then used to identify the index in the underlying array where the key-value pair will be stored. This enables quick retrieval of values based on their keys.
- Null keys and values: HashMap supports a single null key and multiple null values. However, it would help to exercise caution while utilizing invalid keys because they can create unexpected behavior and collisions.
- Performance: Assuming a suitable hash function and uniformly distributed keys, HashMap delivers constant time complexity (O(1)) for simple operations like get(), put(), and remove() on average. In the worst-case situation, however, performance can decrease to O(n), where n is the number of key-value pairs.
- Iteration: HashMap contains methods for iterating over its keys, values, or entries, such as keySet(), values(), and entrySet().
Example:
package week1.day2;
import java.util.HashMap;
public class Calculator {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Luffy", 100);
scores.put("Koby", 90);
scores.put("Ace", 80);
System.out.println("Luffy's score: " + scores.get("Luffy"));
scores.put("Zoro", 95);
scores.remove("Koby");
System.out.println("Does Luffy exist? " + scores.containsKey("Luffy"));
for (String key : scores.keySet()) {
System.out.println(key + ": " + scores.get(key));
}
scores.clear();
}
}
- Here we created the hashmap with the scores object.
- Using the scores object, we can use the put() method to insert the respected key and value.
- We can get the value based on the key using the get method.
- Using the remove method, we can remove a key-value pair.
- We can also receive a boolean response using the containsKey.
- Using for-each, we iterated through the scores key-value pair and printed it.
- Finally, we clear all the key-value pairs using the clear method.
Output:
Luffy's score: 100
Does Luffy exist? true
Ace: 80
Luffy: 100
Zoro: 95
- Log in to post comments