Java HashMap: Efficient Key/Value Pair Storage
Learn about Java HashMap, a versatile data structure that stores items in key/value pairs, enabling quick access to values using various key types, including strings. Explore how HashMap optimizes performance with its fast retrieval capabilities and discover best practices for implementing this powerful collection in your Java applications.
Java HashMap
In Java, a HashMap stores items in key/value pairs, allowing access to values using keys of different types, such as strings.
Syntax
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap capitalCities = new HashMap();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}
Output
{Norway=Oslo, Germany=Berlin, USA=Washington DC, England=London}
HashMap Methods
The HashMap class provides various methods for adding, accessing, and manipulating key-value pairs:
put()
: Adds a key-value pair to the HashMap.get()
: Retrieves the value associated with a specified key.remove()
: Removes the key-value pair associated with a specified key.clear()
: Removes all key-value pairs from the HashMap.size()
: Returns the number of key-value pairs in the HashMap.
Loop Through a HashMap
You can iterate over a HashMap using for-each loops to access keys and values:
Loop Through HashMap
// Print keys
for (String i : capitalCities.keySet()) {
System.out.println(i);
}
// Print values
for (String i : capitalCities.values()) {
System.out.println(i);
}
// Print keys and values
for (String i : capitalCities.keySet()) {
System.out.println("key: " + i + " value: " + capitalCities.get(i));
}
Other Types
HashMap can store keys and values of different types by specifying appropriate wrapper classes for primitive types:
Example with Integer Values
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called people
HashMap people = new HashMap();
// Add keys and values (Name, Age)
people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);
for (String i : people.keySet()) {
System.out.println("key: " + i + " value: " + people.get(i));
}
}
}