Hashmap in Java
HashMap in Java
HashMap is a part of the Java Collections Framework and is an implementation of the Map interface. It provides a key-value pair data structure, where elements are stored as a combination of keys and their associated values. HashMap does not allow duplicate keys, but it allows multiple values to be mapped to the same key. It offers constant-time performance for basic operations like adding, removing, and retrieving elements.
Declaration and Initialization
To use a HashMap in Java, you need to import the java.util.HashMap
package. Here's an example of declaring and initializing a HashMap:
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<String, Integer> studentScores = new HashMap<>();
// Adding key-value pairs to the HashMap
studentScores.put("Alice1", 90);
studentScores.put("Bob1", 85);
studentScores.put("Charlie1", 78);
// No duplicate keys allowed, the value for "Bob1" will be updated
studentScores.put("Bob1", 92);
// Accessing values using keys
System.out.println("Charlie1's score: " + studentScores.get("Charlie1")); // Output: Charlie1's score: 78
// Checking if a key exists
boolean exists = studentScores.containsKey("Alice1");
System.out.println("Is Alice1 a student? " + exists); // Output: Is Alice1 a student? true
// Removing key-value pairs
studentScores.remove("Bob1");
// Iterating over key-value pairs
for (String student : studentScores.keySet()) {
int score = studentScores.get(student);
System.out.println(student + ": " + score);
}
}
}
Common HashMap Operations
Here are some commonly used operations with HashMaps:
put(key, value)
: Adds a key-value pair to the HashMap.get(key)
: Retrieves the value associated with the specified key.containsKey(key)
: Checks if the HashMap contains a specific key.remove(key)
: Removes the key-value pair with the specified key.size()
: Returns the number of key-value pairs in the HashMap.